This is an automated email from the ASF dual-hosted git repository.

DImuthuUpe pushed a commit to branch jupyter-ui-poc
in repository https://gitbox.apache.org/repos/asf/airavata.git


The following commit(s) were added to refs/heads/jupyter-ui-poc by this push:
     new c970e24169 Integrating the support to connect to remote jupyter server 
using linkspan
c970e24169 is described below

commit c970e24169cbbb069e81cd647b20e957c2163cc7
Author: DImuthuUpe <[email protected]>
AuthorDate: Mon Nov 9 22:10:19 2026 -0500

    Integrating the support to connect to remote jupyter server using linkspan
---
 INSTALL.md                                       |   5 +-
 api/process/controller/link.go                   | 141 ++++++++++++
 api/process/dto/link.go                          |  32 +++
 api/process/model/link.go                        |  53 +++++
 api/process/repository/link.go                   |  49 ++++
 api/process/service/link.go                      | 172 ++++++++++++++
 dashboard/README.md                              |   5 +-
 dashboard/src/app/globals.css                    |  15 +-
 dashboard/src/app/notebooks/page.tsx             |   2 +-
 dashboard/src/components/NotebookView.tsx        | 276 +++++++++++++++++++++--
 dashboard/src/lib/types.ts                       |  10 +
 docs/application.md                              |   2 +-
 docs/notebooks.md                                |  70 ++++++
 go.mod                                           |   1 +
 go.sum                                           |   2 +
 internal/app/app.go                              |  10 +-
 internal/config/config.go                        |   5 +
 internal/db/migrate.go                           |   3 +
 internal/db/migrations/0013_process_links.sql    |   7 +
 internal/link/link.go                            | 228 +++++++++++++++++++
 internal/orchestration/engine.go                 |   3 +-
 internal/orchestration/tasks/batch/batch.go      |  97 +++++++-
 internal/orchestration/tasks/batch/slurm.go      |  17 ++
 internal/orchestration/tasks/batch/slurm_test.go |  39 +++-
 internal/server/link_test.go                     | 236 +++++++++++++++++++
 internal/server/server.go                        |   3 +-
 internal/server/server_test.go                   |   2 +-
 website/sidebars.js                              |   2 +-
 28 files changed, 1436 insertions(+), 51 deletions(-)

diff --git a/INSTALL.md b/INSTALL.md
index b9b8c96b4d..4c8cdfbb5c 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -98,6 +98,7 @@ compose database.
 | `AIRAVATA_DASHBOARD_ENABLED` | `true` | Serve the [dashboard](#dashboard) 
under `/dashboard/`. |
 | `AIRAVATA_DASHBOARD_DIR` | `dashboard/out` | The dashboard's built static 
export, relative to the working directory. |
 | `AIRAVATA_CORS_ALLOWED_ORIGINS` | `*` | Comma-separated allowed origins. The 
server echoes the caller's origin rather than sending `*`, because every 
authenticated call carries an `Authorization` header and browsers reject the 
wildcard for credentialed requests. |
+| `AIRAVATA_PUBLIC_URL` | `http://localhost:<SERVER_PORT>` | Where compute 
nodes reach this server. A job running 
[Linkspan](https://github.com/cyber-shuttle/linkspan) links back to its `ws(s)` 
form so the dashboard can open the job's Jupyter Server 
([docs/notebooks.md](docs/notebooks.md)). Set it to the public `https://` URL 
in production. |
 
 ### Database
 
@@ -336,7 +337,9 @@ in the browser on Pyodide, with an `airavata(path)` helper 
that calls this API a
 signed-in user, and a file browser to create, rename, upload and download 
notebooks and
 files. Notebooks and files are kept in each browser's storage, not on the 
server, and the
 kernel downloads Pyodide from the jsDelivr CDN when it first starts, so 
browsers using it
-need internet access.
+need internet access. The page can instead run notebooks on a cluster, in the 
Jupyter
+Server of a running process whose job runs Linkspan, reached through this 
server over
+Linkspan's link ([docs/notebooks.md](docs/notebooks.md)).
 
 It is built as a static export and served by the API server itself under
 `/dashboard/`, so it starts and stops with the server, on the same origin — 
there is no
diff --git a/api/process/controller/link.go b/api/process/controller/link.go
new file mode 100644
index 0000000000..b198f7e54c
--- /dev/null
+++ b/api/process/controller/link.go
@@ -0,0 +1,141 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package controller
+
+import (
+       "log/slog"
+       "net/http"
+       "net/http/httputil"
+       "strconv"
+       "strings"
+
+       "github.com/coder/websocket"
+
+       "github.com/apache/airavata/internal/httpx"
+       "github.com/apache/airavata/internal/link"
+
+       "github.com/apache/airavata/api/process/service"
+)
+
+// LinkController serves the routes that make Airavata a process's Linkspan 
control
+// plane: the link Linkspan dials, the owner's Jupyter access, and the Jupyter 
proxy.
+//
+// The link and the proxy sit outside bearer authentication, each opened by a 
secret
+// issued to the process: the link by its link token, offered as a WebSocket
+// subprotocol, and the proxy by its Jupyter token, which Jupyter clients send 
as
+// "Authorization: token …" or, on WebSockets, as ?token=. Neither header is a 
bearer
+// token, so the auth middleware lets both through as anonymous.
+type LinkController struct {
+       svc   *service.LinkService
+       proxy *httputil.ReverseProxy
+}
+
+// NewLinkController returns a handler delegating to svc.
+func NewLinkController(svc *service.LinkService) *LinkController {
+       return &LinkController{
+               svc: svc,
+               proxy: &httputil.ReverseProxy{
+                       Transport: svc.Registry().Transport(),
+                       // The target was set on the request by jupyter; 
Rewrite only keeps the
+                       // client's forwarding headers out.
+                       Rewrite: func(out *httputil.ProxyRequest) {
+                               out.Out.URL.Scheme = "http"
+                               out.Out.URL.Host = out.In.URL.Host
+                               out.Out.Host = out.In.Host
+                       },
+                       ErrorHandler: func(w http.ResponseWriter, r 
*http.Request, err error) {
+                               slog.Warn("Jupyter proxy could not reach the 
process's server", "path", r.URL.Path, "error", err)
+                               httpx.WriteJSON(w, http.StatusBadGateway, 
map[string]string{
+                                       "error":   "Bad Gateway",
+                                       "message": "The process's Jupyter 
Server could not be reached: its job is not linked to Airavata, or its server 
has not started",
+                               })
+                       },
+               },
+       }
+}
+
+// Register mounts the link routes.
+func (h *LinkController) Register(mux *http.ServeMux) {
+       mux.HandleFunc("GET /api/v1/processes/{processId}/link", h.link)
+       mux.HandleFunc("GET /api/v1/processes/{processId}/jupyter-server", 
h.jupyterServer)
+       mux.HandleFunc("/api/v1/processes/{processId}/jupyter/", h.jupyter)
+}
+
+// link admits the WebSocket a process's Linkspan dials and holds it as the 
process's
+// link until it closes.
+func (h *LinkController) link(w http.ResponseWriter, r *http.Request) {
+       processID := r.PathValue("processId")
+       if !h.svc.Authenticate(r.Context(), processID, link.OfferedToken(r)) {
+               httpx.WriteError(w, r, httpx.Unauthorized("The link token is 
not the one issued to process %s", processID))
+               return
+       }
+       conn, err := websocket.Accept(w, r, 
&websocket.AcceptOptions{Subprotocols: []string{link.Protocol}})
+       if err != nil {
+               return
+       }
+       defer conn.CloseNow()
+       // yamux frames span WebSocket messages freely; the default 32 KiB 
message limit
+       // is Linkspan's own write size, so lift it rather than depend on that.
+       conn.SetReadLimit(-1)
+
+       ctx := r.Context()
+       slog.Info("Linkspan linked", "processId", processID, "remote", 
r.RemoteAddr)
+       _ = h.svc.Registry().Serve(ctx, processID, websocket.NetConn(ctx, conn, 
websocket.MessageBinary))
+       slog.Info("Linkspan link closed", "processId", processID)
+}
+
+// jupyterServer returns the owner's access to the process's Jupyter Server.
+func (h *LinkController) jupyterServer(w http.ResponseWriter, r *http.Request) 
{
+       resp, err := h.svc.JupyterServer(r.Context(), r.PathValue("processId"))
+       if err != nil {
+               httpx.WriteError(w, r, err)
+               return
+       }
+       httpx.WriteJSON(w, http.StatusOK, resp)
+}
+
+// jupyter proxies the Jupyter Server API, kernel WebSockets included, to the 
server
+// the process's job runs, over its link. The token is left on the request: the
+// Jupyter Server checks it again.
+func (h *LinkController) jupyter(w http.ResponseWriter, r *http.Request) {
+       processID := r.PathValue("processId")
+       token := r.URL.Query().Get("token")
+       if scheme, value, found := strings.Cut(r.Header.Get("Authorization"), " 
"); found && strings.EqualFold(scheme, "token") {
+               token = strings.TrimSpace(value)
+       }
+       port, ok := h.svc.JupyterPort(r.Context(), processID, token)
+       if !ok {
+               httpx.WriteError(w, r, httpx.Unauthorized("The Jupyter token is 
not the one issued to process %s", processID))
+               return
+       }
+
+       prefix := "/api/v1/processes/" + processID + "/jupyter"
+       out := r.Clone(r.Context())
+       out.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
+       out.URL.RawPath = ""
+       if out.URL.Path == "" {
+               out.URL.Path = "/"
+       }
+       out.URL.Host = link.Host(processID, port)
+       // The Jupyter Server sees itself addressed on its own loopback port.
+       out.Host = "127.0.0.1:" + strconv.Itoa(int(port))
+       h.proxy.ServeHTTP(w, out)
+}
diff --git a/api/process/dto/link.go b/api/process/dto/link.go
new file mode 100644
index 0000000000..bc2859e0b8
--- /dev/null
+++ b/api/process/dto/link.go
@@ -0,0 +1,32 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package dto
+
+// JupyterServerResponse is how the dashboard opens a process's Jupyter 
Server: through
+// Airavata's proxy at BaseURL (a path under the API root), with Token as the 
Jupyter
+// token. Linked says whether the job's Linkspan currently holds its link; 
until it
+// does, the proxy answers 502.
+type JupyterServerResponse struct {
+       ProcessID string `json:"processId"`
+       Linked    bool   `json:"linked"`
+       BaseURL   string `json:"baseUrl"`
+       Token     string `json:"token"`
+}
diff --git a/api/process/model/link.go b/api/process/model/link.go
new file mode 100644
index 0000000000..a5c43574d0
--- /dev/null
+++ b/api/process/model/link.go
@@ -0,0 +1,53 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package model
+
+// ProcessLink is what lets a process's Linkspan link back to Airavata: the 
secrets its
+// job is handed at submission and the loopback ports its servers listen on.
+//
+// Linkspan, running as the job, dials /api/v1/processes/{id}/link and offers 
the link
+// token; Airavata then reaches the job's servers over that one WebSocket. 
Only the
+// token's digest is kept, since Airavata only ever compares it. The Jupyter 
token is
+// kept as issued: it is handed to the process owner so the dashboard can open 
the
+// job's Jupyter Server through Airavata.
+//
+// A process has at most one row, replaced on each submission, so a 
resubmitted job's
+// predecessor can no longer link. Nothing here is serialised: the row never 
leaves the
+// server except as the owner's Jupyter access.
+type ProcessLink struct {
+       ProcessID string   
`gorm:"column:process_id;primaryKey;type:varchar(36)" json:"-"`
+       Process   *Process 
`gorm:"references:ID;constraint:OnDelete:CASCADE,OnUpdate:CASCADE" json:"-"`
+
+       // LinkTokenHash is the hex SHA-256 of the link token.
+       LinkTokenHash string `gorm:"column:link_token_hash;type:varchar(64);not 
null" json:"-"`
+       JupyterToken  string `gorm:"column:jupyter_token;type:varchar(64);not 
null" json:"-"`
+
+       // The loopback ports, on the job's node, of Linkspan's control API and 
of the
+       // Jupyter Server the job starts. Chosen by Airavata so it knows where 
to dial.
+       ControlPort int32 `gorm:"column:control_port;not null" json:"-"`
+       JupyterPort int32 `gorm:"column:jupyter_port;not null" json:"-"`
+
+       // When the tokens were issued, in milliseconds since the epoch.
+       IssuedAt int64 `gorm:"column:issued_at;not null" json:"-"`
+}
+
+// TableName returns the table backing ProcessLink.
+func (ProcessLink) TableName() string { return "process_links" }
diff --git a/api/process/repository/link.go b/api/process/repository/link.go
new file mode 100644
index 0000000000..d45e1e26e1
--- /dev/null
+++ b/api/process/repository/link.go
@@ -0,0 +1,49 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package repository
+
+import (
+       "context"
+
+       "gorm.io/gorm"
+
+       model "github.com/apache/airavata/api/process/model"
+)
+
+// LinkRepository persists the link secrets issued to each process's job.
+type LinkRepository struct{ db *gorm.DB }
+
+// NewLinkRepository returns a repository over db.
+func NewLinkRepository(db *gorm.DB) *LinkRepository { return 
&LinkRepository{db: db} }
+
+// FindByProcessID returns the process's link, or gorm.ErrRecordNotFound.
+func (r *LinkRepository) FindByProcessID(ctx context.Context, processID 
string) (*model.ProcessLink, error) {
+       var out model.ProcessLink
+       if err := r.db.WithContext(ctx).First(&out, "process_id = ?", 
processID).Error; err != nil {
+               return nil, err
+       }
+       return &out, nil
+}
+
+// Save inserts the link or replaces the process's existing one.
+func (r *LinkRepository) Save(ctx context.Context, link *model.ProcessLink) 
error {
+       return r.db.WithContext(ctx).Save(link).Error
+}
diff --git a/api/process/service/link.go b/api/process/service/link.go
new file mode 100644
index 0000000000..2a3457b4aa
--- /dev/null
+++ b/api/process/service/link.go
@@ -0,0 +1,172 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package service
+
+import (
+       "context"
+       "crypto/rand"
+       "crypto/sha256"
+       "crypto/subtle"
+       "encoding/base64"
+       "encoding/hex"
+       "fmt"
+       "net/url"
+       "strings"
+       "time"
+
+       "github.com/apache/airavata/internal/auth"
+       "github.com/apache/airavata/internal/httpx"
+       "github.com/apache/airavata/internal/link"
+
+       dto "github.com/apache/airavata/api/process/dto"
+       model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/api/process/repository"
+)
+
+// LinkService makes Airavata the control plane a job's Linkspan links to, in 
the role
+// cs-plane plays for CyberShuttle: it issues each submission its link and 
Jupyter
+// tokens, admits the WebSocket that offers the link token, and opens the 
job's Jupyter
+// Server to the process owner through a proxy.
+type LinkService struct {
+       links     *repository.LinkRepository
+       processes *repository.ProcessRepository
+       registry  *link.Registry
+       publicURL string
+}
+
+// NewLinkService returns a link service. publicURL is where jobs reach this 
server,
+// http(s)://host[:port]; the link URL is its ws(s) form.
+func NewLinkService(links *repository.LinkRepository, processes 
*repository.ProcessRepository, registry *link.Registry, publicURL string) 
*LinkService {
+       return &LinkService{links: links, processes: processes, registry: 
registry, publicURL: strings.TrimRight(publicURL, "/")}
+}
+
+// Registry is the live links this service admits.
+func (s *LinkService) Registry() *link.Registry { return s.registry }
+
+// LinkURL is the WebSocket URL a process's Linkspan dials.
+func (s *LinkService) LinkURL(processID string) (string, error) {
+       u, err := url.Parse(s.publicURL)
+       if err != nil || u.Host == "" {
+               return "", fmt.Errorf("public URL %q is not an absolute http(s) 
URL", s.publicURL)
+       }
+       switch u.Scheme {
+       case "http":
+               u.Scheme = "ws"
+       case "https":
+               u.Scheme = "wss"
+       default:
+               return "", fmt.Errorf("public URL %q is not an absolute http(s) 
URL", s.publicURL)
+       }
+       return u.JoinPath("api/v1/processes", url.PathEscape(processID), 
"link").String(), nil
+}
+
+// Issue mints the link and Jupyter tokens for a submission of the process, 
replacing
+// any issued before, and returns what the job is handed.
+func (s *LinkService) Issue(ctx context.Context, processID string) 
(*link.Issued, error) {
+       linkURL, err := s.LinkURL(processID)
+       if err != nil {
+               return nil, err
+       }
+       linkToken, err := newSecret()
+       if err != nil {
+               return nil, err
+       }
+       jupyterToken, err := newSecret()
+       if err != nil {
+               return nil, err
+       }
+       control, jupyter := link.Ports(processID)
+       if err := s.links.Save(ctx, &model.ProcessLink{
+               ProcessID:     processID,
+               LinkTokenHash: digest(linkToken),
+               JupyterToken:  jupyterToken,
+               ControlPort:   int32(control),
+               JupyterPort:   int32(jupyter),
+               IssuedAt:      time.Now().UnixMilli(),
+       }); err != nil {
+               return nil, err
+       }
+       return &link.Issued{URL: linkURL, LinkToken: linkToken, JupyterToken: 
jupyterToken, ControlPort: control, JupyterPort: jupyter}, nil
+}
+
+// Authenticate reports whether token is the link token last issued to the 
process.
+func (s *LinkService) Authenticate(ctx context.Context, processID, token 
string) bool {
+       if token == "" {
+               return false
+       }
+       found, err := s.links.FindByProcessID(ctx, processID)
+       if err != nil {
+               return false
+       }
+       return subtle.ConstantTimeCompare([]byte(digest(token)), 
[]byte(found.LinkTokenHash)) == 1
+}
+
+// JupyterServer returns the caller's access to their process's Jupyter 
Server. Only
+// the owner may have it: the token runs code as the owner's cluster account.
+func (s *LinkService) JupyterServer(ctx context.Context, processID string) 
(*dto.JupyterServerResponse, error) {
+       principal, err := auth.RequireAuthenticated(ctx)
+       if err != nil {
+               return nil, err
+       }
+       process, err := s.processes.FindByID(ctx, processID)
+       if err != nil {
+               return nil, notFoundAs(err, "Process %s not found", processID)
+       }
+       if !process.OwnedBy(principal.Name) {
+               return nil, httpx.Forbidden("Only the owner of process %s can 
open its Jupyter Server", processID)
+       }
+       found, err := s.links.FindByProcessID(ctx, processID)
+       if err != nil {
+               return nil, notFoundAs(err, "Process %s has not been submitted, 
so it has no Jupyter Server", processID)
+       }
+       return &dto.JupyterServerResponse{
+               ProcessID: processID,
+               Linked:    s.registry.Linked(processID),
+               BaseURL:   "/api/v1/processes/" + url.PathEscape(processID) + 
"/jupyter/",
+               Token:     found.JupyterToken,
+       }, nil
+}
+
+// JupyterPort returns the port of the process's Jupyter Server when token is 
its
+// Jupyter token, and false otherwise.
+func (s *LinkService) JupyterPort(ctx context.Context, processID, token 
string) (uint16, bool) {
+       if token == "" {
+               return 0, false
+       }
+       found, err := s.links.FindByProcessID(ctx, processID)
+       if err != nil || subtle.ConstantTimeCompare([]byte(token), 
[]byte(found.JupyterToken)) != 1 {
+               return 0, false
+       }
+       return uint16(found.JupyterPort), true
+}
+
+func newSecret() (string, error) {
+       b := make([]byte, 32)
+       if _, err := rand.Read(b); err != nil {
+               return "", err
+       }
+       return base64.RawURLEncoding.EncodeToString(b), nil
+}
+
+func digest(token string) string {
+       sum := sha256.Sum256([]byte(token))
+       return hex.EncodeToString(sum[:])
+}
diff --git a/dashboard/README.md b/dashboard/README.md
index 70ab23d196..34b3bcf3b6 100644
--- a/dashboard/README.md
+++ b/dashboard/README.md
@@ -33,8 +33,9 @@ src/lib/interactive-auth.tsx
 src/lib/types.ts     wire shapes, mirroring api/*/dto
 src/components/NotebookView.tsx, NotebookFiles.tsx
                      the Notebooks page: a file browser and a 
@datalayer/jupyter-react
-                     notebook on an in-browser Pyodide kernel; files live in 
the
-                     browser's IndexedDB through jupyter-react's lite contents 
service
+                     notebook, either on an in-browser Pyodide kernel with 
files in
+                     the browser's IndexedDB, or on the Jupyter Server of a 
process's
+                     Linkspan job, through the API's /processes/{id}/jupyter/ 
proxy
 ```
 
 The build uses webpack (`next build --webpack`), not Turbopack: the JupyterLab 
packages
diff --git a/dashboard/src/app/globals.css b/dashboard/src/app/globals.css
index 5c53299a3d..b30196e7d0 100644
--- a/dashboard/src/app/globals.css
+++ b/dashboard/src/app/globals.css
@@ -954,7 +954,20 @@ dd.chips {
   }
 }
 
-/* Notebooks: a file browser beside the open notebook. */
+/* Notebooks: where they run, then a file browser beside the open notebook. */
+.nb-source {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: center;
+  gap: 8px 12px;
+}
+.nb-source label {
+  font-weight: 600;
+}
+.nb-source select {
+  width: auto;
+  max-width: 100%;
+}
 .nb-workspace {
   display: grid;
   grid-template-columns: 280px minmax(0, 1fr);
diff --git a/dashboard/src/app/notebooks/page.tsx 
b/dashboard/src/app/notebooks/page.tsx
index 21a0a24485..bb549341dd 100644
--- a/dashboard/src/app/notebooks/page.tsx
+++ b/dashboard/src/app/notebooks/page.tsx
@@ -16,7 +16,7 @@ export default function NotebooksPage() {
     <div className="stack">
       <PageHead
         title="Notebooks"
-        sub="Python notebooks that run entirely in your browser on Pyodide. 
Notebooks and files are kept in this browser, not on the server."
+        sub="Python notebooks that run in your browser on Pyodide, or on a 
cluster in the Jupyter Server of a running process whose job runs Linkspan."
       />
       <NotebookView />
     </div>
diff --git a/dashboard/src/components/NotebookView.tsx 
b/dashboard/src/components/NotebookView.tsx
index 3ed26db62b..6ccaaf2021 100644
--- a/dashboard/src/components/NotebookView.tsx
+++ b/dashboard/src/components/NotebookView.tsx
@@ -1,14 +1,18 @@
 "use client";
 
-import { JupyterReactTheme, Notebook, NotebookToolbar, useJupyter } from 
"@datalayer/jupyter-react";
-import type { Kernel } from "@datalayer/jupyter-react";
+import { createLiteServiceManager, JupyterReactTheme, Kernel, Notebook, 
NotebookToolbar } from "@datalayer/jupyter-react";
 import { PageConfig } from "@jupyterlab/coreutils";
 import type { INotebookContent } from "@jupyterlab/nbformat";
 import type { NotebookModel } from "@jupyterlab/notebook";
-import type { Contents, ServiceManager } from "@jupyterlab/services";
+import { ServerConnection, ServiceManager } from "@jupyterlab/services";
+import type { Contents } from "@jupyterlab/services";
 import { useEffect, useMemo, useRef, useState } from "react";
-import { API_BASE, getToken } from "@/lib/api";
+import { API_BASE, api, ApiError, errorText, getToken } from "@/lib/api";
+import { latestStatus, useDeploymentNames, withStatuses } from "@/lib/catalog";
+import { useResource } from "@/lib/hooks";
+import type { JupyterServer, Process } from "@/lib/types";
 import { isNotebook, NotebookFiles } from "./NotebookFiles";
+import { Alert } from "./ui";
 
 // jupyter-react's lite server registers a service worker at the origin root, 
which would
 // sit in front of every request to the API server. It only syncs files 
between the
@@ -16,10 +20,16 @@ import { isNotebook, NotebookFiles } from "./NotebookFiles";
 // treats it as optional. Disable it before the lite server starts.
 
PageConfig.Extension.disabled.push("@jupyterlite/server-extension:service-worker");
 
-// The last notebook opened, reopened on the next visit (a per-browser 
convenience).
+// Where notebooks run: in this browser on Pyodide, or on the Jupyter Server a
+// process's job started, reached through Airavata over the job's Linkspan 
link.
+type Source = { kind: "browser" } | { kind: "process"; processId: string };
+
+// The source chosen last, and the notebook open last in each (per-browser 
conveniences).
+const SOURCE_KEY = "airavata.notebook.source";
 const LAST_OPEN_KEY = "airavata.notebook.open";
 const WELCOME_PATH = "Welcome.ipynb";
 const SAVE_DELAY_MS = 1000;
+const LINK_POLL_MS = 5000;
 
 // Run in the kernel when it starts, so cells can call the Airavata API as the 
signed-in
 // user: `await airavata("/api/v1/...")`. The kernel is a Pyodide web worker 
on this
@@ -76,21 +86,30 @@ const WELCOME: INotebookContent = {
   ],
 };
 
-function readLastOpen(): string | null {
+function readStored(key: string): string | null {
   try {
-    return window.localStorage.getItem(LAST_OPEN_KEY);
+    return window.localStorage.getItem(key);
   } catch {
     return null;
   }
 }
 
-function writeLastOpen(path: string | null) {
+function writeStored(key: string, value: string | null) {
   try {
-    if (path) window.localStorage.setItem(LAST_OPEN_KEY, path);
-    else window.localStorage.removeItem(LAST_OPEN_KEY);
+    if (value) window.localStorage.setItem(key, value);
+    else window.localStorage.removeItem(key);
   } catch {}
 }
 
+function readSource(): Source {
+  const id = readStored(SOURCE_KEY);
+  return id ? { kind: "process", processId: id } : { kind: "browser" };
+}
+
+function lastOpenKey(source: Source) {
+  return source.kind === "browser" ? LAST_OPEN_KEY : 
`${LAST_OPEN_KEY}.${source.processId}`;
+}
+
 function useColorMode(): "light" | "dark" {
   const [dark, setDark] = useState(() => 
window.matchMedia("(prefers-color-scheme: dark)").matches);
   useEffect(() => {
@@ -102,12 +121,224 @@ function useColorMode(): "light" | "dark" {
   return dark ? "dark" : "light";
 }
 
-// NotebookView is the Notebooks page: a file browser over the in-browser 
contents store
-// beside the open notebook, all on jupyter-react's "lite" mode (a Pyodide 
kernel and
-// IndexedDB-backed contents, no Jupyter server).
+// The in-browser service manager is made once per page load: switching 
sources and
+// back reuses it, and with it the files kept in this browser.
+let liteManager: Promise<ServiceManager.IManager> | null = null;
+function getLiteManager() {
+  liteManager ??= createLiteServiceManager(true);
+  return liteManager;
+}
+
+// A manager for the Jupyter Server behind Airavata's proxy. Jupyter clients 
send the
+// token as "Authorization: token …" on requests and, with appendToken, as 
?token= on
+// WebSockets, which cannot carry headers; Airavata's proxy accepts either.
+function remoteManager(access: JupyterServer): ServiceManager.IManager {
+  const baseUrl = (API_BASE || window.location.origin) + access.baseUrl;
+  const serverSettings = ServerConnection.makeSettings({
+    baseUrl,
+    wsUrl: baseUrl.replace(/^http/, "ws"),
+    token: access.token,
+    appendToken: true,
+  });
+  return new ServiceManager({ serverSettings });
+}
+
+// useKernel starts the default kernel of a service manager, runs initCode in 
it, and
+// shuts it down when the manager changes or the page is left, so a remote job 
is not
+// left holding kernels nobody can reach.
+function useKernel(serviceManager: ServiceManager.IManager | null, initCode: 
string) {
+  const [kernel, setKernel] = useState<Kernel | null>(null);
+  const [error, setError] = useState<string | null>(null);
+  useEffect(() => {
+    if (!serviceManager) return;
+    let cancelled = false;
+    let started: Kernel | null = null;
+    (async () => {
+      await serviceManager.kernelspecs.ready;
+      const name = serviceManager.kernelspecs.specs?.default || "python3";
+      await serviceManager.kernels.ready;
+      if (cancelled) return;
+      started = new Kernel({
+        kernelName: name,
+        kernelSpecName: name,
+        kernelManager: serviceManager.kernels,
+        kernelspecsManager: serviceManager.kernelspecs,
+        sessionManager: serviceManager.sessions,
+      });
+      await started.ready;
+      if (initCode) {
+        try {
+          await started.execute(initCode)?.done;
+        } catch (e) {
+          console.error("Failed to run the kernel's initial code", e);
+        }
+      }
+      if (!cancelled) setKernel(started);
+    })().catch((e) => !cancelled && setError(errorText(e)));
+    return () => {
+      cancelled = true;
+      setKernel(null);
+      setError(null);
+      void started?.shutdown().catch(() => {});
+    };
+  }, [serviceManager, initCode]);
+  return { kernel, error };
+}
+
+// NotebookView is the Notebooks page: a choice of where notebooks run, then a 
file
+// browser over that place's files beside the open notebook.
 export default function NotebookView() {
+  const [source, setSourceState] = useState<Source>(readSource);
+  const setSource = (next: Source) => {
+    writeStored(SOURCE_KEY, next.kind === "process" ? next.processId : null);
+    setSourceState(next);
+  };
+  return (
+    <div className="stack">
+      <SourcePicker source={source} onChange={setSource} />
+      {source.kind === "browser" ? (
+        <BrowserWorkspace key="browser" />
+      ) : (
+        <ProcessWorkspace key={source.processId} processId={source.processId} 
/>
+      )}
+    </div>
+  );
+}
+
+// Processes that may be running a job, which is when a Linkspan in it can 
link.
+const LIVE = new Set(["SUBMITTED", "RUNNING"]);
+
+function SourcePicker({ source, onChange }: { source: Source; onChange: (s: 
Source) => void }) {
+  const names = useDeploymentNames();
+  const rows = useResource(async () => withStatuses(await 
api.get<Process[]>("/api/v1/processes/me")), [], 30_000);
+  const live = (rows.data ?? []).filter(
+    (r) => r.process.processType === "BATCH_JOB" && 
LIVE.has(latestStatus(r)?.status ?? ""),
+  );
+  const selected = source.kind === "process" ? source.processId : "";
+  const listed = live.some((r) => r.process.processId === selected);
+  const label = (p: Process) =>
+    `${names.appName(p.batchProcess?.deploymentId) ?? "Process"} · 
${p.processId.slice(0, 8)}`;
+
+  return (
+    <div className="nb-source">
+      <label htmlFor="nb-source">Run notebooks</label>
+      <select
+        id="nb-source"
+        value={selected}
+        onChange={(e) => onChange(e.target.value ? { kind: "process", 
processId: e.target.value } : { kind: "browser" })}
+      >
+        <option value="">In this browser (Pyodide)</option>
+        {live.map((r) => (
+          <option key={r.process.processId} value={r.process.processId}>
+            On {label(r.process)} ({latestStatus(r)?.status?.toLowerCase()})
+          </option>
+        ))}
+        {selected && !listed && <option value={selected}>On process 
{selected.slice(0, 8)}</option>}
+      </select>
+      <span className="muted">
+        {source.kind === "browser"
+          ? "Files are kept in this browser."
+          : "Files and kernels are on the cluster, in the Jupyter Server the 
process's job started."}
+      </span>
+    </div>
+  );
+}
+
+function BrowserWorkspace() {
+  const [serviceManager, setServiceManager] = useState<ServiceManager.IManager 
| null>(null);
+  useEffect(() => {
+    let cancelled = false;
+    void getLiteManager().then((m) => !cancelled && setServiceManager(m));
+    return () => {
+      cancelled = true;
+    };
+  }, []);
   const code = useMemo(() => initCode(API_BASE || window.location.origin, 
getToken()), []);
-  const { serviceManager, defaultKernel } = useJupyter({ lite: true, 
startDefaultKernel: true, initCode: code });
+  const { kernel, error } = useKernel(serviceManager, code);
+  if (error) return <Alert>The Python kernel did not start: {error}</Alert>;
+  if (!serviceManager || !kernel) return <p className="muted">Starting the 
Python kernel…</p>;
+  return <Workspace serviceManager={serviceManager} kernel={kernel} 
storeKey={LAST_OPEN_KEY} welcome />;
+}
+
+// ProcessWorkspace opens the Jupyter Server of a process's job once its 
Linkspan has
+// linked to Airavata, polling until then; the job may still be queued or 
building its
+// Python environment.
+function ProcessWorkspace({ processId }: { processId: string }) {
+  const [access, setAccess] = useState<JupyterServer | null>(null);
+  const [error, setError] = useState<string | null>(null);
+  useEffect(() => {
+    let cancelled = false;
+    let timer: ReturnType<typeof setTimeout>;
+    const poll = async () => {
+      try {
+        const next = await 
api.get<JupyterServer>(`/api/v1/processes/${processId}/jupyter-server`);
+        if (cancelled) return;
+        setError(null);
+        // Keep the object while nothing changed, so the service manager is 
not rebuilt.
+        setAccess((prev) => (prev && prev.token === next.token && prev.linked 
=== next.linked ? prev : next));
+      } catch (e) {
+        if (cancelled) return;
+        setError(e instanceof ApiError && e.status === 404 ? "This process has 
not been submitted yet." : errorText(e));
+      }
+      timer = setTimeout(poll, LINK_POLL_MS);
+    };
+    void poll();
+    return () => {
+      cancelled = true;
+      clearTimeout(timer);
+    };
+  }, [processId]);
+
+  // One manager per issued token: a resubmitted job's server is a new server. 
It
+  // outlives a dropped link, so the page recovers when Linkspan redials.
+  const token = access?.linked ? access.token : null;
+  const [serviceManager, setServiceManager] = useState<ServiceManager.IManager 
| null>(null);
+  useEffect(() => {
+    if (!token || !access) return;
+    const manager = remoteManager(access);
+    setServiceManager(manager);
+    return () => {
+      setServiceManager(null);
+      manager.dispose();
+    };
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [token]);
+  const { kernel, error: kernelError } = useKernel(serviceManager, "");
+
+  if (error) return <Alert>{error}</Alert>;
+  if (!access) return <p className="muted">Looking up the process…</p>;
+  if (!serviceManager) {
+    return (
+      <Alert kind="info">
+        Waiting for the job&apos;s Linkspan to link to Airavata. This happens 
once the job is running; the first time,
+        it also builds the Jupyter environment, which takes a few minutes.
+      </Alert>
+    );
+  }
+  if (kernelError) return <Alert>The job&apos;s Jupyter Server did not start a 
kernel: {kernelError}</Alert>;
+  if (!kernel) return <p className="muted">Starting a kernel on the 
cluster…</p>;
+  return (
+    <>
+      {!access.linked && <Alert kind="warn">The job&apos;s link to Airavata 
dropped; waiting for Linkspan to redial.</Alert>}
+      <Workspace serviceManager={serviceManager} kernel={kernel} 
storeKey={lastOpenKey({ kind: "process", processId })} />
+    </>
+  );
+}
+
+// Workspace is the file browser beside the open notebook, over one service 
manager's
+// contents and one kernel all its notebooks share. welcome creates the 
welcome notebook
+// in an empty store, which only the browser's own store gets.
+function Workspace({
+  serviceManager,
+  kernel,
+  storeKey,
+  welcome = false,
+}: {
+  serviceManager: ServiceManager.IManager;
+  kernel: Kernel;
+  storeKey: string;
+  welcome?: boolean;
+}) {
   const [openPath, setOpenPathState] = useState<string | null>(null);
   const [ready, setReady] = useState(false);
   // Changes only when a different file is opened, not when the open one is 
renamed, so a
@@ -117,18 +348,17 @@ export default function NotebookView() {
 
   const setOpenPath = (path: string | null, newDoc: boolean) => {
     setOpenPathState(path);
-    writeLastOpen(path);
+    writeStored(storeKey, path);
     if (newDoc) setDocId((d) => d + 1);
   };
 
   // Pick the notebook to show first: the last one opened if it is still 
there, else the
   // welcome notebook, created on the very first visit.
   useEffect(() => {
-    if (!serviceManager) return;
     const contents = serviceManager.contents;
     let cancelled = false;
     (async () => {
-      const last = readLastOpen();
+      const last = readStored(storeKey);
       let path: string | null = null;
       if (last) {
         try {
@@ -136,7 +366,7 @@ export default function NotebookView() {
           path = last;
         } catch {}
       }
-      if (!path) {
+      if (!path && welcome) {
         const root = await contents.get("", { content: true });
         if ((root.content as Contents.IModel[]).length === 0) {
           await contents.save(WELCOME_PATH, { type: "notebook", format: 
"json", content: WELCOME });
@@ -150,11 +380,11 @@ export default function NotebookView() {
     return () => {
       cancelled = true;
     };
+    // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [serviceManager]);
 
   // Follow the open notebook when it, or a folder above it, is renamed or 
deleted.
   useEffect(() => {
-    if (!serviceManager) return;
     const contents = serviceManager.contents;
     const onChange = (_: unknown, change: Contents.IChangedArgs) => {
       if (change.type !== "rename" && change.type !== "delete") return;
@@ -164,7 +394,7 @@ export default function NotebookView() {
         if (!current || (current !== oldPath && !current.startsWith(oldPath + 
"/"))) return current;
         const newPath = change.type === "rename" ? change.newValue?.path : 
undefined;
         const next = newPath ? newPath + current.slice(oldPath.length) : null;
-        writeLastOpen(next);
+        writeStored(storeKey, next);
         return next;
       });
     };
@@ -172,9 +402,9 @@ export default function NotebookView() {
     return () => {
       contents.fileChanged.disconnect(onChange);
     };
-  }, [serviceManager]);
+  }, [serviceManager, storeKey]);
 
-  if (!serviceManager || !defaultKernel || !ready) return <p 
className="muted">Starting the Python kernel…</p>;
+  if (!ready) return <p className="muted">Opening files…</p>;
 
   return (
     <div className="nb-workspace">
@@ -190,7 +420,7 @@ export default function NotebookView() {
             docId={docId}
             path={openPath}
             serviceManager={serviceManager}
-            kernel={defaultKernel}
+            kernel={kernel}
             colorMode={colorMode}
           />
         ) : (
diff --git a/dashboard/src/lib/types.ts b/dashboard/src/lib/types.ts
index ba4595b8b0..ae3813f486 100644
--- a/dashboard/src/lib/types.ts
+++ b/dashboard/src/lib/types.ts
@@ -292,6 +292,16 @@ export interface Process {
   batchProcess: BatchProcess | null;
 }
 
+// How the dashboard opens a process's Jupyter Server: Airavata's proxy at 
baseUrl (a
+// path under the API root), with token as the Jupyter token. linked says 
whether the
+// job's Linkspan holds its link to Airavata right now.
+export interface JupyterServer {
+  processId: string;
+  linked: boolean;
+  baseUrl: string;
+  token: string;
+}
+
 export interface ProcessStatus {
   processStatusId: string;
   processId: string | null;
diff --git a/docs/application.md b/docs/application.md
index 60b7f3152b..98fabac53c 100644
--- a/docs/application.md
+++ b/docs/application.md
@@ -147,7 +147,7 @@ run_alphafold.sh \
 - An output: `{{ outputs.name }}`. Use `{{ outputs["name.ext"] }}` if the name 
contains a dot.
 - Optional inputs can be guarded: `{% if inputs.seed %}--seed {{ 
inputs.seed[0] }}{% endif %}`
 
-Other variables are available too: `work_dir`, `work_dir_quoted`, 
`process_id`, `job_name`, `stdout_file`, `stderr_file`, and the resource values 
(`nodes`, `cpus`, `mem`, `gpus`, …).
+Other variables are available too: `work_dir`, `work_dir_quoted`, 
`process_id`, `job_name`, `stdout_file`, `stderr_file`, and the resource values 
(`nodes`, `cpus`, `mem`, `gpus`, …). A run section that starts Linkspan also 
has `link_url`, `link_control_port` and `link_jupyter_port` and the matching 
environment variables. See [Notebooks on a cluster](notebooks.md).
 
 Shell-style references such as `$fastaFile` are **not** substituted by 
Airavata. They reach the script unchanged and are expanded by bash as ordinary 
environment variables, which are usually empty.
 
diff --git a/docs/notebooks.md b/docs/notebooks.md
new file mode 100644
index 0000000000..5f3d906ab2
--- /dev/null
+++ b/docs/notebooks.md
@@ -0,0 +1,70 @@
+# Notebooks on a cluster
+
+The dashboard's **Notebooks** page runs Python in the browser on Pyodide by 
default. It can also run notebooks on a cluster: on the Jupyter Server that a 
running process's job starts, with the job's files in the file browser and its 
kernels running on the compute node.
+
+The job reaches Airavata the way a 
[CyberShuttle](https://github.com/cyber-shuttle/cs-plane) session reaches 
cs-plane. The job runs [Linkspan](https://github.com/cyber-shuttle/linkspan), 
which dials **out** to Airavata over one WebSocket, the *link*, and Airavata 
reaches the job's Jupyter Server through it. The compute node opens no inbound 
port, and nothing runs on the login node besides the usual `sbatch`.
+
+```
+browser ──HTTPS──▶ Airavata ──link (WebSocket, yamux)──▶ Linkspan 
──loopback──▶ Jupyter Server
+                   /api/v1/processes/{id}/jupyter/      dialled from the job   
     on the compute node
+```
+
+## What every batch job is given
+
+Each time a `BATCH_JOB` process is submitted, Airavata issues it a fresh link 
token and Jupyter token and picks two loopback ports from the process id. It 
writes them to `.airavata-link.env` in the work directory, readable only by the 
cluster account (mode `0600`), and the job script sources that file before the 
run section. The tokens never appear in the script itself, which Airavata logs 
and stores on the job submission task.
+
+| Environment variable | Contents |
+|---|---|
+| `CS_LINK_URL` | The link URL, `wss://<public URL>/api/v1/processes/<process 
id>/link`, built by Airavata for this process |
+| `LINKSPAN_LINK_TOKEN` | The link token, which Linkspan reads from the 
environment |
+| `CS_CONTROL_PORT` | The loopback port for Linkspan's own API |
+| `CS_JUPYTER_PORT` | The loopback port for the Jupyter Server |
+| `JUPYTER_TOKEN` | The Jupyter token, which Linkspan passes to the Jupyter 
Server it starts |
+
+The run section can also read the non-secret values as template variables: `{{ 
link_url }}`, `{{ link_control_port }}` and `{{ link_jupyter_port }}`.
+
+A resubmission is issued new tokens, so an earlier job of the same process can 
no longer link. A job that does not run Linkspan ignores all of this.
+
+Compute nodes must be able to reach Airavata at `AIRAVATA_PUBLIC_URL` (see 
[INSTALL.md](https://github.com/apache/airavata/blob/master/INSTALL.md#server)).
 Use `https://` in production, so the link is `wss://`.
+
+## A deployment that runs Linkspan
+
+Any [application deployment](application.md#application-deployment) can serve 
notebooks. Its run section writes a Linkspan workflow that starts a Jupyter 
Server on `CS_JUPYTER_PORT`, then runs Linkspan with the link transport:
+
+```jinja
+cat > workflow.yaml <<EOF
+tasks:
+  - on: start
+    steps:
+      - name: Jupyter
+        action: jupyter.sessions.start
+        params:
+          root_dir: {{ work_dir }}
+          addr: 127.0.0.1:${CS_JUPYTER_PORT}
+EOF
+
+$HOME/.cybershuttle/bin/linkspan --port "$CS_CONTROL_PORT" --workflow 
workflow.yaml --tunnel-enable --tunnel-mode=link --tunnel-link-args="--url 
$CS_LINK_URL"
+```
+
+This needs Linkspan 0.22.0 or newer, the first release with the link 
transport, installed on the cluster. See [Linkspan's 
README](https://github.com/cyber-shuttle/linkspan#installation). The first 
Jupyter Server on an account builds a Python environment under 
`~/.cybershuttle`, which takes a few minutes and needs outbound access to 
`astral.sh`, `github.com` and `pypi.org`. The job lasts as long as the Jupyter 
Server, or until its walltime.
+
+`root_dir` decides which folder the file browser opens; `{{ work_dir }}` is 
the run's work directory, and any absolute path the account can read works.
+
+## Opening it
+
+On the Notebooks page, **Run notebooks** lists the signed-in user's processes 
that are submitted or running. Choosing one waits for its Linkspan to link, 
then opens the job's Jupyter Server: the file browser shows the job's files, 
and notebooks run on a `python3` kernel on the compute node. The kernel is shut 
down when the page is left or another source is chosen. Choosing **In this 
browser** goes back to Pyodide and the notebooks kept in the browser.
+
+If Airavata restarts, or the link drops, Linkspan redials on its own and the 
page picks the server up again.
+
+## API
+
+| Route | Authentication | Purpose |
+|---|---|---|
+| `GET /api/v1/processes/{processId}/link` | The link token, as the WebSocket 
subprotocol `link.<token>` | Linkspan's link. Airavata selects the subprotocol 
`cybershuttle.v1`. |
+| `GET /api/v1/processes/{processId}/jupyter-server` | Bearer token of the 
process owner | `{processId, linked, baseUrl, token}`: where to reach the 
Jupyter Server and its token |
+| `/api/v1/processes/{processId}/jupyter/…` | The Jupyter token, as 
`Authorization: token <token>` or `?token=` | Proxy to the job's Jupyter 
Server, including kernel WebSockets. `502` while the job is not linked. |
+
+Only the owner of a process can read its Jupyter token, because the token runs 
code as the owner's cluster account. The proxy compares the token before 
forwarding, and the Jupyter Server checks it again. Airavata's bearer tokens 
are never sent to the job. Other users on a shared node can reach the job's 
loopback ports, but they still need the Jupyter token to use the server 
([Linkspan's security 
model](https://github.com/cyber-shuttle/linkspan/blob/main/SECURITY.md#security-model)).
+
+The link protocol is Linkspan's, as frozen in its [compatibility 
document](https://github.com/cyber-shuttle/linkspan/blob/main/docs/COMPATIBILITY.md):
 yamux runs over binary WebSocket frames, with Airavata as the yamux client. 
For each stream Airavata writes the target port as two big-endian bytes, and 
Linkspan answers `1` and carries the stream if one of its own servers listens 
there, or answers `0`.
+
diff --git a/go.mod b/go.mod
index d27ca9f5d2..71010a85e8 100644
--- a/go.mod
+++ b/go.mod
@@ -43,6 +43,7 @@ require (
        github.com/golang-migrate/migrate/v4 v4.16.2 // indirect
        github.com/hashicorp/errwrap v1.1.0 // indirect
        github.com/hashicorp/go-multierror v1.1.1 // indirect
+       github.com/hashicorp/yamux v0.1.2 // indirect
        github.com/jackc/pgpassfile v1.0.0 // indirect
        github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // 
indirect
        github.com/jackc/pgx/v5 v5.7.5 // indirect
diff --git a/go.sum b/go.sum
index 403a394897..1a5c8e6e56 100644
--- a/go.sum
+++ b/go.sum
@@ -87,6 +87,8 @@ github.com/hashicorp/errwrap v1.1.0 
h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY
 github.com/hashicorp/errwrap v1.1.0/go.mod 
h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
 github.com/hashicorp/go-multierror v1.1.1 
h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
 github.com/hashicorp/go-multierror v1.1.1/go.mod 
h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/hashicorp/yamux v0.1.2 
h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
+github.com/hashicorp/yamux v0.1.2/go.mod 
h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
 github.com/hpcloud/tail v1.0.0/go.mod 
h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
 github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod 
h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
 github.com/jackc/pgpassfile v1.0.0 
h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
diff --git a/internal/app/app.go b/internal/app/app.go
index 8f6acf625b..2411f99176 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -32,6 +32,7 @@ import (
        "gorm.io/gorm"
 
        "github.com/apache/airavata/internal/config"
+       "github.com/apache/airavata/internal/link"
 
        applicationrepo "github.com/apache/airavata/api/application/repository"
        applicationsvc "github.com/apache/airavata/api/application/service"
@@ -109,6 +110,7 @@ type Services struct {
        // Launch is a higher-level service that orchestrates the other 
services to submit
        // a process and its tasks, and to monitor the job until it completes.
        Launch *processsvc.LaunchService
+       Link   *processsvc.LinkService
 
        ExecutionEngine *orchestration.ExecutionEngine
 }
@@ -138,6 +140,7 @@ type Repositories struct {
        JobSubmissionTasks      *processrepo.JobSubmissionTaskRepository
        JobMonitoringTasks      *processrepo.JobMonitoringTaskRepository
        InteractiveCommandTasks *processrepo.InteractiveCommandTaskRepository
+       Links                   *processrepo.LinkRepository
 }
 
 func NewRepositories(db *gorm.DB) *Repositories {
@@ -166,6 +169,7 @@ func NewRepositories(db *gorm.DB) *Repositories {
                JobSubmissionTasks:      
processrepo.NewJobSubmissionTaskRepository(db),
                JobMonitoringTasks:      
processrepo.NewJobMonitoringTaskRepository(db),
                InteractiveCommandTasks: 
processrepo.NewInteractiveCommandTaskRepository(db),
+               Links:                   processrepo.NewLinkRepository(db),
        }
 }
 
@@ -222,8 +226,10 @@ func NewServices(cfg config.Config, db *gorm.DB, repos 
*Repositories, workflowBa
        virtualDataDirectorySharingSvc := 
datasvc.NewVirtualDataDirectorySharingService(db, virtualDirs, shares, groups, 
users, groupMembers)
        sshCredentialSvc := 
credentialssvc.NewSSHCredentialService(sshCredentials, users, clusterConfigs, 
storages)
 
+       linkSvc := processsvc.NewLinkService(repos.Links, processes, 
link.NewRegistry(), cfg.PublicURL)
+
        executionEngine := orchestration.NewExecutionEngine(stagingTasks, 
submissionTasks,
-               monitoringTasks, storages, clusterConfigs, processes, 
deployments, templates, batchStatus, statuses, repos.TaskStatuses, 
processWorkflows, workflowBackend, sshContext)
+               monitoringTasks, storages, clusterConfigs, processes, 
deployments, templates, batchStatus, statuses, repos.TaskStatuses, 
processWorkflows, workflowBackend, sshContext, linkSvc)
        executionEngine.StartEngine()
 
        return &Services{
@@ -275,6 +281,8 @@ func NewServices(cfg config.Config, db *gorm.DB, repos 
*Repositories, workflowBa
                        sshCredentialSvc, scpDataStorageSvc, dataProductSvc, 
statusSvc, stagingTasks, submissionTasks,
                        monitoringTasks, commandTasks, processWorkflows, 
executionEngine),
 
+               Link: linkSvc,
+
                ExecutionEngine: executionEngine,
        }
 }
diff --git a/internal/config/config.go b/internal/config/config.go
index 261a0d6c69..1ae9cb089d 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -65,6 +65,10 @@ type Config struct {
        // DashboardDir is the dashboard's static export (dashboard/out after 
"npm run
        // build"), served under /dashboard/ alongside the API. Empty disables 
it.
        DashboardDir string
+
+       // PublicURL is where compute nodes reach this server, 
http(s)://host[:port]. A
+       // job's Linkspan dials its ws(s) form to link back; see internal/link.
+       PublicURL string
 }
 
 // Load reads configuration from the environment, applying the same defaults 
the Java
@@ -89,6 +93,7 @@ func load() (Config, error) {
                WorkflowBackendType:       
env("AIRAVATA_WORKFLOW_BACKEND_TYPE", "sqlite"),
                WorkflowBackendSqlitePath: 
env("AIRAVATA_WORKFLOW_BACKEND_SQLITE_PATH", 
"/tmp/airavataorchestrator.sqlite"),
                DashboardDir:              dashboardDir(),
+               PublicURL:                 env("AIRAVATA_PUBLIC_URL", 
"http://localhost:"+env("SERVER_PORT", "9095")),
        }
 
        // Without a root account and without CILogon credentials there is no 
way to
diff --git a/internal/db/migrate.go b/internal/db/migrate.go
index d492dc59aa..4dae12b3b1 100644
--- a/internal/db/migrate.go
+++ b/internal/db/migrate.go
@@ -107,6 +107,9 @@ func Entities() []any {
                // The workflow runs started for a process. Like ProcessStatus 
it is referenced
                // back from Process, through LastWorkflowID, which carries no 
constraint.
                &processmodel.ProcessWorkflow{},
+
+               // The secrets a process's job is handed so its Linkspan can 
link back.
+               &processmodel.ProcessLink{},
        }
 }
 
diff --git a/internal/db/migrations/0013_process_links.sql 
b/internal/db/migrations/0013_process_links.sql
new file mode 100644
index 0000000000..dd8b25f0e0
--- /dev/null
+++ b/internal/db/migrations/0013_process_links.sql
@@ -0,0 +1,7 @@
+-- The secrets a process's job is handed so its Linkspan can link back to 
Airavata:
+-- the digest of the link token, the Jupyter token the owner opens the job's 
Jupyter
+-- Server with, and the loopback ports its servers listen on. One row per 
process,
+-- replaced on each submission. The DDL is what AutoMigrate emits for 
ProcessLink —
+-- see TestBaselineMigrationMatchesAutoMigrate.
+
+CREATE TABLE "process_links" ("process_id" varchar(36),"link_token_hash" 
varchar(64) NOT NULL,"jupyter_token" varchar(64) NOT NULL,"control_port" 
integer NOT NULL,"jupyter_port" integer NOT NULL,"issued_at" bigint NOT 
NULL,PRIMARY KEY ("process_id"),CONSTRAINT "fk_process_links_process" FOREIGN 
KEY ("process_id") REFERENCES "processes"("process_id") ON DELETE CASCADE ON 
UPDATE CASCADE);
diff --git a/internal/link/link.go b/internal/link/link.go
new file mode 100644
index 0000000000..caed44533c
--- /dev/null
+++ b/internal/link/link.go
@@ -0,0 +1,228 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package link holds the WebSockets Linkspan dials back to Airavata and 
reaches a job's
+// servers through them.
+//
+// It speaks Linkspan's link protocol, the one cs-plane defined
+// 
(https://github.com/cyber-shuttle/linkspan/blob/main/docs/COMPATIBILITY.md): one
+// WebSocket per job, offering the subprotocols cybershuttle.v1 and 
link.<token> and
+// carrying yamux in binary frames, with Airavata as the yamux client. For 
each stream
+// Airavata writes the target port as two big-endian bytes; Linkspan answers 1 
when it
+// connected to a server it runs on that loopback port, else 0, and then 
carries bytes
+// until either end closes. yamux's keepalive detects a dead link, and 
Linkspan redials.
+//
+// The registry is process-local. When Airavata restarts, every Linkspan 
redials.
+package link
+
+import (
+       "context"
+       "crypto/sha256"
+       "encoding/binary"
+       "errors"
+       "fmt"
+       "io"
+       "net"
+       "net/http"
+       "strconv"
+       "strings"
+       "sync"
+       "time"
+
+       "github.com/hashicorp/yamux"
+)
+
+// Protocol is the WebSocket subprotocol Linkspan offers and the link endpoint 
selects.
+const Protocol = "cybershuttle.v1"
+
+// TokenPrefix marks the subprotocol that carries the link token.
+const TokenPrefix = "link."
+
+// hostSuffix is the pseudo-domain of the addresses Transport dials: <process 
id>.process.
+const hostSuffix = ".process"
+
+// ErrNotLinked reports a process whose Linkspan holds no link to this server.
+var ErrNotLinked = errors.New("the process's Linkspan is not linked to 
Airavata")
+
+// Registry holds the live link of each process.
+type Registry struct {
+       mu    sync.Mutex
+       links map[string]*yamux.Session
+}
+
+// NewRegistry returns an empty registry.
+func NewRegistry() *Registry {
+       return &Registry{links: map[string]*yamux.Session{}}
+}
+
+// Serve runs conn, the WebSocket a process's Linkspan opened, as that 
process's link
+// until it ends or ctx is done. A newer link replaces an older one: the older 
is
+// closed, since only one job of the process holds valid tokens at a time and a
+// redialling Linkspan should not be refused by its own stale socket.
+func (r *Registry) Serve(ctx context.Context, processID string, conn net.Conn) 
error {
+       config := yamux.DefaultConfig()
+       config.LogOutput = io.Discard
+       session, err := yamux.Client(conn, config)
+       if err != nil {
+               _ = conn.Close()
+               return err
+       }
+
+       r.mu.Lock()
+       previous := r.links[processID]
+       r.links[processID] = session
+       r.mu.Unlock()
+       if previous != nil {
+               _ = previous.Close()
+       }
+
+       select {
+       case <-session.CloseChan():
+       case <-ctx.Done():
+               _ = session.Close()
+       }
+
+       r.mu.Lock()
+       if r.links[processID] == session {
+               delete(r.links, processID)
+       }
+       r.mu.Unlock()
+       return nil
+}
+
+// Linked reports whether the process currently holds a link.
+func (r *Registry) Linked(processID string) bool {
+       return r.session(processID) != nil
+}
+
+func (r *Registry) session(processID string) *yamux.Session {
+       r.mu.Lock()
+       defer r.mu.Unlock()
+       session := r.links[processID]
+       if session != nil && session.IsClosed() {
+               return nil
+       }
+       return session
+}
+
+// Dial opens a stream to the server the process's job runs on loopback port.
+func (r *Registry) Dial(ctx context.Context, processID string, port uint16) 
(net.Conn, error) {
+       session := r.session(processID)
+       if session == nil {
+               return nil, ErrNotLinked
+       }
+       stream, err := session.OpenStream()
+       if err != nil {
+               return nil, err
+       }
+       stop := context.AfterFunc(ctx, func() { _ = stream.Close() })
+       defer stop()
+
+       // The handshake is bounded on its own: a wedged Linkspan must not hold 
a proxied
+       // request open until the caller gives up.
+       _ = stream.SetDeadline(time.Now().Add(30 * time.Second))
+       frame := binary.BigEndian.AppendUint16(nil, port)
+       if _, err = stream.Write(frame); err == nil {
+               _, err = io.ReadFull(stream, frame[:1])
+       }
+       if err == nil && frame[0] != 1 {
+               err = fmt.Errorf("the process's Linkspan runs no server on port 
%d", port)
+       }
+       if err != nil {
+               _ = stream.Close()
+               return nil, err
+       }
+       _ = stream.SetDeadline(time.Time{})
+       return stream, nil
+}
+
+// Host is the address Transport dials to reach port on the process's job.
+func Host(processID string, port uint16) string {
+       return processID + hostSuffix + ":" + strconv.Itoa(int(port))
+}
+
+// Transport returns an HTTP transport whose connections are streams over the 
links,
+// for addresses made by Host. It pools them per process and port, and carries
+// WebSocket upgrades, so a reverse proxy over it serves a Jupyter Server 
whole.
+func (r *Registry) Transport() *http.Transport {
+       return &http.Transport{
+               DialContext: func(ctx context.Context, _, address string) 
(net.Conn, error) {
+                       host, rawPort, err := net.SplitHostPort(address)
+                       if err != nil {
+                               return nil, err
+                       }
+                       processID, ok := strings.CutSuffix(host, hostSuffix)
+                       port, perr := strconv.ParseUint(rawPort, 10, 16)
+                       if !ok || processID == "" || perr != nil {
+                               return nil, fmt.Errorf("%s is not a process 
address", address)
+                       }
+                       return r.Dial(ctx, processID, uint16(port))
+               },
+               MaxIdleConnsPerHost:   8,
+               IdleConnTimeout:       90 * time.Second,
+               ResponseHeaderTimeout: 5 * time.Minute,
+       }
+}
+
+// Ports derives the loopback ports a process's job serves on: Linkspan's 
control API
+// and, one above it, the Jupyter Server. They are a function of the process 
id, in
+// 20000–39999, so Airavata knows them before the job starts. A job sharing a 
node with
+// another that drew the same port fails to start its server, as with any 
fixed port.
+func Ports(processID string) (control, jupyter uint16) {
+       sum := sha256.Sum256([]byte(processID))
+       base := 20000 + int(binary.BigEndian.Uint16(sum[:2]))%19999
+       return uint16(base), uint16(base + 1)
+}
+
+// OfferedToken returns the link token among the subprotocols a WebSocket 
upgrade
+// offered, or "".
+func OfferedToken(r *http.Request) string {
+       for _, offered := range r.Header.Values("Sec-WebSocket-Protocol") {
+               for _, p := range strings.Split(offered, ",") {
+                       if token, ok := strings.CutPrefix(strings.TrimSpace(p), 
TokenPrefix); ok {
+                               return token
+                       }
+               }
+       }
+       return ""
+}
+
+// Issued is what a process's job is handed so its Linkspan can link: where to 
dial,
+// the token to offer, and the ports and Jupyter token its servers use.
+type Issued struct {
+       URL          string
+       LinkToken    string
+       JupyterToken string
+       ControlPort  uint16
+       JupyterPort  uint16
+}
+
+// Env is the job environment that carries Issued, under the names Linkspan 
reads
+// (LINKSPAN_LINK_TOKEN, JUPYTER_TOKEN) and the ones its documented job script 
uses
+// (CS_LINK_URL, CS_CONTROL_PORT), plus CS_JUPYTER_PORT for the workflow's 
addr.
+func (i *Issued) Env() map[string]string {
+       return map[string]string{
+               "CS_LINK_URL":         i.URL,
+               "CS_CONTROL_PORT":     strconv.Itoa(int(i.ControlPort)),
+               "CS_JUPYTER_PORT":     strconv.Itoa(int(i.JupyterPort)),
+               "LINKSPAN_LINK_TOKEN": i.LinkToken,
+               "JUPYTER_TOKEN":       i.JupyterToken,
+       }
+}
diff --git a/internal/orchestration/engine.go b/internal/orchestration/engine.go
index 2f76c27f7c..35686c709b 100644
--- a/internal/orchestration/engine.go
+++ b/internal/orchestration/engine.go
@@ -75,6 +75,7 @@ func NewExecutionEngine(dataStagingTasks 
*processrepo.DataStagingTaskRepository,
        processWorkflows *processrepo.WorkflowRepository,
        workflowBackend backend.Backend,
        sshContext *ssh.GlobalSSHContext,
+       links batch.LinkIssuer,
 ) *ExecutionEngine {
 
        // workflowBackend may be nil in tests to prevent sqlite driver 
collision. Only create
@@ -89,7 +90,7 @@ func NewExecutionEngine(dataStagingTasks 
*processrepo.DataStagingTaskRepository,
        return &ExecutionEngine{
                workflows: workflows.New(
                        data.New(processes, dataStagingTasks, scpStorages, 
slurmClusterConfigs, sshContext, tracker),
-                       batch.New(processes, jobSubmissionTasks, 
slurmClusterConfigs, batchDeployments, templates, batchStatus, sshContext, 
tracker),
+                       batch.New(processes, jobSubmissionTasks, 
slurmClusterConfigs, batchDeployments, templates, batchStatus, sshContext, 
tracker, links),
                        monitoring.New(processes, jobMonitoringTasks, tracker),
                        dataStagingTasks, jobSubmissionTasks, 
jobMonitoringTasks, processStatus,
                        processWorkflows,
diff --git a/internal/orchestration/tasks/batch/batch.go 
b/internal/orchestration/tasks/batch/batch.go
index f2a5dd23dc..9a340194a3 100644
--- a/internal/orchestration/tasks/batch/batch.go
+++ b/internal/orchestration/tasks/batch/batch.go
@@ -29,6 +29,7 @@ import (
        "os"
        "path"
        "regexp"
+       "sort"
        "strings"
        "time"
 
@@ -37,10 +38,23 @@ import (
        computerepo "github.com/apache/airavata/api/compute/repository"
        model "github.com/apache/airavata/api/process/model"
        processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/link"
        "github.com/apache/airavata/internal/orchestration/execution"
        ssh "github.com/apache/airavata/internal/ssh"
 )
 
+// LinkIssuer mints the secrets a submission's job is handed so a Linkspan it 
runs can
+// link back to Airavata. It is process/service.LinkService.
+type LinkIssuer interface {
+       Issue(ctx context.Context, processID string) (*link.Issued, error)
+}
+
+// linkEnvFile is the file, in the job's working directory, that carries the 
issued
+// link secrets into the job. It is written mode 0600 and sourced by the 
script, so
+// the tokens never appear in the script, which is logged, stored on the task 
and left
+// readable on the cluster.
+const linkEnvFile = ".airavata-link.env"
+
 // Tasks carries out the batch tasks of a process. Its methods are workflow 
activities.
 type Tasks struct {
        processes           *processrepo.ProcessRepository
@@ -51,6 +65,7 @@ type Tasks struct {
        batchStatus         *processrepo.BatchJobStatusRepository
        sshContext          *ssh.GlobalSSHContext
        tracker             *execution.TaskTracker
+       links               LinkIssuer
 }
 
 // New returns the batch tasks over the given repositories.
@@ -62,6 +77,7 @@ func New(processes *processrepo.ProcessRepository,
        batchStatus *processrepo.BatchJobStatusRepository,
        sshContext *ssh.GlobalSSHContext,
        tracker *execution.TaskTracker,
+       links LinkIssuer,
 ) *Tasks {
        return &Tasks{
                processes:           processes,
@@ -72,6 +88,7 @@ func New(processes *processrepo.ProcessRepository,
                batchStatus:         batchStatus,
                sshContext:          sshContext,
                tracker:             tracker,
+               links:               links,
        }
 }
 
@@ -104,7 +121,26 @@ func (a *Tasks) submitBatchJob(ctx context.Context, 
executionContext *execution.
                return nil, err
        }
 
-       script, err := a.slurmScript(ctx, process, 
executionContext.GlobalJobConfigs)
+       if jst.WorkingDir == nil || strings.TrimSpace(*jst.WorkingDir) == "" {
+               err := fmt.Errorf("job submission task %s of process %s names 
no working directory", taskID, processID)
+               slog.Error("Failed to submit batch job", "taskId", taskID, 
"processId", processID, "error", err)
+               return nil, err
+       }
+
+       // Each submission is issued fresh link secrets, so a job from an 
earlier
+       // submission of the process can no longer link.
+       var issued *link.Issued
+       envFilePath := ""
+       if a.links != nil {
+               issued, err = a.links.Issue(ctx, processID)
+               if err != nil {
+                       slog.Error("Failed to issue link secrets for batch 
job", "taskId", taskID, "processId", processID, "error", err)
+                       return nil, err
+               }
+               envFilePath = path.Join(*jst.WorkingDir, linkEnvFile)
+       }
+
+       script, err := a.slurmScript(ctx, process, 
executionContext.GlobalJobConfigs, issued, envFilePath)
        if err != nil {
                slog.Error("Failed to build slurm script for submitting batch 
job", "taskId", taskID, "processId", processID, "error", err)
                return nil, err
@@ -112,15 +148,12 @@ func (a *Tasks) submitBatchJob(ctx context.Context, 
executionContext *execution.
 
        slog.Info("Built slurm script for batch job", "taskId", taskID, 
"processId", processID, "script", script)
 
-       // Recorded before submitting, so the script can be inspected even when 
the
-       // submission fails. A retry builds and records it afresh.
        jst.Script = &script
        if err := a.jobSubmissionTasks.Save(ctx, jst); err != nil {
                slog.Error("Failed to record slurm script on job submission 
task", "taskId", taskID, "processId", processID, "error", err)
                return nil, err
        }
 
-       // save script to a temporary location or a known path before uploading
        scriptPath := fmt.Sprintf("/tmp/%s.slurm", processID)
        err = os.WriteFile(scriptPath, []byte(script), 0644)
        if err != nil {
@@ -138,12 +171,6 @@ func (a *Tasks) submitBatchJob(ctx context.Context, 
executionContext *execution.
 
        slog.Info("Retrieved slurm cluster config for batch job", "taskId", 
taskID, "processId", processID, "clusterConfigId", clusterConfig.ID)
 
-       if jst.WorkingDir == nil || strings.TrimSpace(*jst.WorkingDir) == "" {
-               err := fmt.Errorf("job submission task %s of process %s names 
no working directory", taskID, processID)
-               slog.Error("Failed to submit batch job", "taskId", taskID, 
"processId", processID, "error", err)
-               return nil, err
-       }
-
        dialConfig := ssh.NewSSHDialConfig(
                clusterConfig.SlurmCluster.HeadnodeHost,
                clusterConfig.SlurmCluster.HeadnodePort,
@@ -159,6 +186,13 @@ func (a *Tasks) submitBatchJob(ctx context.Context, 
executionContext *execution.
                return nil, err
        }
 
+       if issued != nil {
+               if err := a.uploadLinkEnv(ctx, dialConfig, issued, 
envFilePath); err != nil {
+                       slog.Error("Failed to upload link secrets to cluster", 
"taskId", taskID, "processId", processID, "remotePath", envFilePath, "error", 
err)
+                       return nil, err
+               }
+       }
+
        scriptUploadPath := path.Join(*jst.WorkingDir, "script.slurm")
        slog.Info("Uploading slurm script to cluster", "taskId", taskID, 
"processId", processID, "scriptPath", scriptPath, "remotePath", 
scriptUploadPath)
        if err := ssh.UploadFileToSCP(ctx, dialConfig, a.sshContext, 
scriptPath, scriptUploadPath); err != nil {
@@ -245,7 +279,46 @@ func parseSbatchJobID(out string) (string, error) {
 }
 
 // slurmScript gathers what a submission script is built from and renders it.
-func (a *Tasks) slurmScript(ctx context.Context, process *model.Process, 
globalJobConfigs *execution.GlobalJobConfigs) (string, error) {
+// uploadLinkEnv writes the issued link secrets to remotePath as shell 
exports, mode
+// 0600. scp keeps the local file's mode on a file it creates, and the remote 
file is
+// removed first so an existing one's wider mode is not inherited.
+func (a *Tasks) uploadLinkEnv(ctx context.Context, dialConfig 
ssh.SSHDialConfig, issued *link.Issued, remotePath string) error {
+       env := issued.Env()
+       names := make([]string, 0, len(env))
+       for name := range env {
+               names = append(names, name)
+       }
+       sort.Strings(names)
+       var b strings.Builder
+       b.WriteString("# Written by Airavata for this job's Linkspan. Do not 
share.\n")
+       for _, name := range names {
+               b.WriteString("export " + name + "=" + 
ssh.ShellQuote(env[name]) + "\n")
+       }
+
+       local, err := os.CreateTemp("", "airavata-link-*.env")
+       if err != nil {
+               return err
+       }
+       defer os.Remove(local.Name())
+       if _, err := local.WriteString(b.String()); err != nil {
+               local.Close()
+               return err
+       }
+       if err := local.Close(); err != nil {
+               return err
+       }
+       if err := os.Chmod(local.Name(), 0600); err != nil {
+               return err
+       }
+
+       if _, _, err := ssh.RunSSHCommand(ctx, dialConfig, a.sshContext, "rm -f 
"+ssh.ShellQuote(remotePath),
+               "ssh rm "+remotePath); err != nil {
+               return err
+       }
+       return ssh.UploadFileToSCP(ctx, dialConfig, a.sshContext, local.Name(), 
remotePath)
+}
+
+func (a *Tasks) slurmScript(ctx context.Context, process *model.Process, 
globalJobConfigs *execution.GlobalJobConfigs, issued *link.Issued, envFilePath 
string) (string, error) {
        batch := process.BatchProcess
 
        if batch.DeploymentID == nil {
@@ -270,7 +343,7 @@ func (a *Tasks) slurmScript(ctx context.Context, process 
*model.Process, globalJ
        }
 
        slog.Info("Building slurm script for process", "processId", process.ID)
-       return buildSlurmScript(process, deployment, template, clusterConfig, 
globalJobConfigs)
+       return buildSlurmScript(process, deployment, template, clusterConfig, 
globalJobConfigs, issued, envFilePath)
 }
 
 func (a *Tasks) CancelBatchJob(ctx context.Context, executionContext 
*execution.Context, processID string, taskID string) (*execution.Context, 
error) {
diff --git a/internal/orchestration/tasks/batch/slurm.go 
b/internal/orchestration/tasks/batch/slurm.go
index 2f478a758c..585ef9761d 100644
--- a/internal/orchestration/tasks/batch/slurm.go
+++ b/internal/orchestration/tasks/batch/slurm.go
@@ -32,6 +32,7 @@ import (
        appmodel "github.com/apache/airavata/api/application/model"
        computemodel "github.com/apache/airavata/api/compute/model"
        model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/internal/link"
        "github.com/apache/airavata/internal/orchestration/execution"
        ssh "github.com/apache/airavata/internal/ssh"
 )
@@ -91,6 +92,9 @@ const slurmScriptTemplate = `#!/bin/bash
 
 echo "Airavata process {{ process_id }} starting on $(hostname) at $(date)"
 cd {{ work_dir_quoted }} || exit 1
+{% if link_env_file %}
+. {{ link_env_file_quoted }} || exit 1
+{% endif %}
 
 {{ run_section }}
 airavata_status=$?
@@ -106,6 +110,8 @@ func buildSlurmScript(
        template *appmodel.Template,
        clusterConfig *computemodel.SlurmClusterConfig,
        globalJobConfigs *execution.GlobalJobConfigs,
+       issued *link.Issued,
+       linkEnvFile string,
 ) (string, error) {
        batchProcess := process.BatchProcess
 
@@ -164,6 +170,17 @@ func buildSlurmScript(
                "outputs": outputs,
        }
 
+       // The link back to Airavata, for a run section that starts Linkspan. 
The tokens
+       // are not here: they reach the job only through the sourced env file, 
as
+       // $LINKSPAN_LINK_TOKEN and $JUPYTER_TOKEN.
+       if issued != nil && linkEnvFile != "" {
+               ctx["link_env_file"] = linkEnvFile
+               ctx["link_env_file_quoted"] = ssh.ShellQuote(linkEnvFile)
+               ctx["link_url"] = issued.URL
+               ctx["link_control_port"] = int(issued.ControlPort)
+               ctx["link_jupyter_port"] = int(issued.JupyterPort)
+       }
+
        // A directive is one line, so a value carrying a newline would not 
extend the
        // directive — it would start a fresh line in the script that Slurm or 
the shell
        // reads as something else entirely. The values interpolated into the 
#SBATCH block
diff --git a/internal/orchestration/tasks/batch/slurm_test.go 
b/internal/orchestration/tasks/batch/slurm_test.go
index 4e87c90d7d..ff1ef89ff1 100644
--- a/internal/orchestration/tasks/batch/slurm_test.go
+++ b/internal/orchestration/tasks/batch/slurm_test.go
@@ -27,6 +27,7 @@ import (
        appmodel "github.com/apache/airavata/api/application/model"
        computemodel "github.com/apache/airavata/api/compute/model"
        model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/internal/link"
        "github.com/apache/airavata/internal/orchestration/execution"
 )
 
@@ -100,7 +101,7 @@ func TestBuildSlurmScript(t *testing.T) {
                MailUser: "[email protected]",
        }
 
-       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg)
+       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg, nil, "")
        if err != nil {
                t.Fatalf("buildSlurmScript: %v", err)
        }
@@ -151,7 +152,7 @@ func TestBuildSlurmScriptFallsBackToDeploymentConfig(t 
*testing.T) {
                MailUser: "[email protected]",
        }
 
-       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg)
+       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg, nil, "")
        if err != nil {
                t.Fatalf("buildSlurmScript: %v", err)
        }
@@ -173,7 +174,7 @@ func TestBuildSlurmScriptHonoursBaseWorkDir(t *testing.T) {
                MailUser: "[email protected]",
        }
 
-       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg)
+       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg, nil, "")
        if err != nil {
                t.Fatalf("buildSlurmScript: %v", err)
        }
@@ -192,7 +193,7 @@ func TestBuildSlurmScriptDoesNotReexpandInputValues(t 
*testing.T) {
                MailUser: "[email protected]",
        }
 
-       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg)
+       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg, nil, "")
        if err != nil {
                t.Fatalf("buildSlurmScript: %v", err)
        }
@@ -263,7 +264,35 @@ func TestBuildSlurmScriptRejectsLineBreaks(t *testing.T) {
                MailUser: "[email protected]",
        }
 
-       if _, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg); err == nil {
+       if _, err := buildSlurmScript(process, deployment, template, 
clusterConfig, &cfg, nil, ""); err == nil {
                t.Fatal("expected a work dir spanning lines to be refused")
        }
 }
+
+// A job issued a link sources its secrets from the env file, and the run 
section sees
+// the link URL and ports but never a token.
+func TestBuildSlurmScriptSourcesTheLinkEnvFile(t *testing.T) {
+       process, deployment, template, clusterConfig := scriptFixture()
+       deployment.SlurmRunSection = `linkspan --port {{ link_control_port }} 
--tunnel-link-args="--url {{ link_url }}" # jupyter {{ link_jupyter_port }}`
+       issued := &link.Issued{
+               URL: "wss://airavata.example.org/api/v1/processes/proc-1/link", 
LinkToken: "link-secret",
+               JupyterToken: "jupyter-secret", ControlPort: 21000, 
JupyterPort: 21001,
+       }
+
+       script, err := buildSlurmScript(process, deployment, template, 
clusterConfig,
+               &execution.GlobalJobConfigs{}, issued, 
"/scratch/airavata/proc-1/.airavata-link.env")
+       if err != nil {
+               t.Fatalf("buildSlurmScript: %v", err)
+       }
+       for _, line := range []string{
+               "cd '/scratch/airavata/proc-1' || exit 1\n. 
'/scratch/airavata/proc-1/.airavata-link.env' || exit 1\n",
+               `linkspan --port 21000 --tunnel-link-args="--url 
wss://airavata.example.org/api/v1/processes/proc-1/link" # jupyter 21001`,
+       } {
+               if !strings.Contains(script, line) {
+                       t.Errorf("script is missing %q\n---\n%s", line, script)
+               }
+       }
+       if strings.Contains(script, "secret") {
+               t.Errorf("script carries a token\n---\n%s", script)
+       }
+}
diff --git a/internal/server/link_test.go b/internal/server/link_test.go
new file mode 100644
index 0000000000..0dfcc50a49
--- /dev/null
+++ b/internal/server/link_test.go
@@ -0,0 +1,236 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package server_test
+
+import (
+       "context"
+       "encoding/binary"
+       "encoding/json"
+       "io"
+       "net"
+       "net/http"
+       "net/http/httptest"
+       "strings"
+       "testing"
+       "time"
+
+       "github.com/coder/websocket"
+       "github.com/hashicorp/yamux"
+
+       "github.com/apache/airavata/internal/link"
+)
+
+// fakeJupyter stands in for the Jupyter Server a job's Linkspan starts: it 
reports
+// the path and Host it was asked for, and echoes on a WebSocket.
+func fakeJupyter(t *testing.T) *httptest.Server {
+       t.Helper()
+       mux := http.NewServeMux()
+       mux.HandleFunc("GET /api/status", func(w http.ResponseWriter, r 
*http.Request) {
+               _ = json.NewEncoder(w).Encode(map[string]string{
+                       "path": r.URL.Path, "host": r.Host, "authorization": 
r.Header.Get("Authorization"),
+               })
+       })
+       mux.HandleFunc("GET /api/kernels/k1/channels", func(w 
http.ResponseWriter, r *http.Request) {
+               conn, err := websocket.Accept(w, r, nil)
+               if err != nil {
+                       return
+               }
+               defer conn.CloseNow()
+               for {
+                       kind, data, err := conn.Read(r.Context())
+                       if err != nil {
+                               return
+                       }
+                       if err := conn.Write(r.Context(), kind, 
append([]byte("echo:"), data...)); err != nil {
+                               return
+                       }
+               }
+       })
+       srv := httptest.NewServer(mux)
+       t.Cleanup(srv.Close)
+       return srv
+}
+
+// fakeLinkspan dials the link as Linkspan does and carries each stream for 
port to
+// target, refusing every other port.
+func fakeLinkspan(t *testing.T, ctx context.Context, linkURL, token string, 
port uint16, target string) error {
+       t.Helper()
+       conn, resp, err := websocket.Dial(ctx, linkURL, 
&websocket.DialOptions{Subprotocols: []string{link.Protocol, link.TokenPrefix + 
token}})
+       if resp != nil && resp.Body != nil {
+               resp.Body.Close()
+       }
+       if err != nil {
+               return err
+       }
+       conn.SetReadLimit(-1)
+       session, err := yamux.Server(websocket.NetConn(ctx, conn, 
websocket.MessageBinary), nil)
+       if err != nil {
+               return err
+       }
+       go func() {
+               defer session.Close()
+               for {
+                       stream, err := session.Accept()
+                       if err != nil {
+                               return
+                       }
+                       go func() {
+                               defer stream.Close()
+                               var frame [2]byte
+                               if _, err := io.ReadFull(stream, frame[:]); err 
!= nil {
+                                       return
+                               }
+                               if binary.BigEndian.Uint16(frame[:]) != port {
+                                       _, _ = stream.Write([]byte{0})
+                                       return
+                               }
+                               server, err := net.Dial("tcp", target)
+                               if err != nil {
+                                       _, _ = stream.Write([]byte{0})
+                                       return
+                               }
+                               defer server.Close()
+                               _, _ = stream.Write([]byte{1})
+                               go func() { _, _ = io.Copy(server, stream); 
server.Close() }()
+                               _, _ = io.Copy(stream, server)
+                       }()
+               }
+       }()
+       return nil
+}
+
+func TestLinkCarriesTheJupyterServerToItsOwner(t *testing.T) {
+       h := newHarness(t)
+       processID := h.seedProcess("link", tokenAlice)
+       ctx, cancel := context.WithCancel(context.Background())
+       defer cancel()
+
+       issued, err := h.svcs.Link.Issue(ctx, processID)
+       if err != nil {
+               t.Fatalf("issue: %v", err)
+       }
+       if want := "wss://airavata.example.org/api/v1/processes/" + processID + 
"/link"; issued.URL != want {
+               t.Errorf("link URL = %q, want %q", issued.URL, want)
+       }
+       control, jupyterPort := link.Ports(processID)
+       if issued.ControlPort != control || issued.JupyterPort != jupyterPort 
|| control < 20000 || jupyterPort > 40000 {
+               t.Errorf("ports = %d/%d, want %d/%d in range", 
issued.ControlPort, issued.JupyterPort, control, jupyterPort)
+       }
+
+       api := httptest.NewServer(h.srv)
+       defer api.Close()
+       wsBase := "ws" + strings.TrimPrefix(api.URL, "http")
+       linkURL := wsBase + "/api/v1/processes/" + processID + "/link"
+       jupyter := fakeJupyter(t)
+       proxy := api.URL + "/api/v1/processes/" + processID + "/jupyter"
+
+       get := func(path, authorization string) (*http.Response, 
map[string]string) {
+               req, _ := http.NewRequest(http.MethodGet, proxy+path, nil)
+               if authorization != "" {
+                       req.Header.Set("Authorization", authorization)
+               }
+               resp, err := http.DefaultClient.Do(req)
+               if err != nil {
+                       t.Fatalf("GET %s: %v", path, err)
+               }
+               defer resp.Body.Close()
+               var body map[string]string
+               _ = json.NewDecoder(resp.Body).Decode(&body)
+               return resp, body
+       }
+
+       // Before Linkspan links, the proxy has nowhere to go.
+       if resp, _ := get("/api/status", "token "+issued.JupyterToken); 
resp.StatusCode != http.StatusBadGateway {
+               t.Errorf("unlinked proxy: status = %d, want 502", 
resp.StatusCode)
+       }
+
+       // A wrong link token is refused before the upgrade.
+       if err := fakeLinkspan(t, ctx, linkURL, "not-the-token", jupyterPort, 
jupyter.Listener.Addr().String()); err == nil {
+               t.Fatal("link with a wrong token was admitted")
+       }
+       if err := fakeLinkspan(t, ctx, linkURL, issued.LinkToken, jupyterPort, 
jupyter.Listener.Addr().String()); err != nil {
+               t.Fatalf("link: %v", err)
+       }
+
+       // Only the owner is handed the Jupyter token, and sees the link once 
it is up.
+       if rec := h.do(http.MethodGet, 
"/api/v1/processes/"+processID+"/jupyter-server", tokenBob, nil); rec.Code != 
http.StatusForbidden {
+               t.Errorf("non-owner jupyter-server: status = %d, want 403", 
rec.Code)
+       }
+       deadline := time.Now().Add(5 * time.Second)
+       var access map[string]any
+       for {
+               access = h.mustDo(http.MethodGet, 
"/api/v1/processes/"+processID+"/jupyter-server", tokenAlice, nil, 
http.StatusOK)
+               if access["linked"] == true || time.Now().After(deadline) {
+                       break
+               }
+               time.Sleep(20 * time.Millisecond)
+       }
+       if access["linked"] != true || access["token"] != issued.JupyterToken ||
+               access["baseUrl"] != "/api/v1/processes/"+processID+"/jupyter/" 
{
+               t.Fatalf("jupyter-server = %v", access)
+       }
+
+       // The proxy wants the Jupyter token, not a bearer token.
+       if resp, _ := get("/api/status", ""); resp.StatusCode != 
http.StatusUnauthorized {
+               t.Errorf("no token: status = %d, want 401", resp.StatusCode)
+       }
+       if resp, _ := get("/api/status", "Bearer "+tokenAlice); resp.StatusCode 
!= http.StatusUnauthorized {
+               t.Errorf("bearer token: status = %d, want 401", resp.StatusCode)
+       }
+       resp, body := get("/api/status", "token "+issued.JupyterToken)
+       if resp.StatusCode != http.StatusOK {
+               t.Fatalf("proxied status = %d, want 200", resp.StatusCode)
+       }
+       if want := "127.0.0.1:" + itoa(jupyterPort); body["path"] != 
"/api/status" || body["host"] != want ||
+               body["authorization"] != "token "+issued.JupyterToken {
+               t.Errorf("Jupyter Server saw %v", body)
+       }
+
+       // Kernel channels are WebSockets with the token in the query.
+       wsURL := wsBase + "/api/v1/processes/" + processID + 
"/jupyter/api/kernels/k1/channels?token=" + issued.JupyterToken
+       kernel, wsResp, err := websocket.Dial(ctx, wsURL, nil)
+       if wsResp != nil && wsResp.Body != nil {
+               wsResp.Body.Close()
+       }
+       if err != nil {
+               t.Fatalf("kernel websocket: %v", err)
+       }
+       defer kernel.CloseNow()
+       if err := kernel.Write(ctx, websocket.MessageText, []byte("hello")); 
err != nil {
+               t.Fatalf("write: %v", err)
+       }
+       if _, got, err := kernel.Read(ctx); err != nil || string(got) != 
"echo:hello" {
+               t.Errorf("kernel echo = %q, %v", got, err)
+       }
+
+       // A resubmission is issued new tokens; the old ones open nothing.
+       if _, err := h.svcs.Link.Issue(ctx, processID); err != nil {
+               t.Fatalf("reissue: %v", err)
+       }
+       if resp, _ := get("/api/status", "token "+issued.JupyterToken); 
resp.StatusCode != http.StatusUnauthorized {
+               t.Errorf("stale Jupyter token: status = %d, want 401", 
resp.StatusCode)
+       }
+}
+
+func itoa(n uint16) string {
+       b, _ := json.Marshal(n)
+       return string(b)
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index b75ed964f9..0682bb9f54 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -79,6 +79,7 @@ func New(cfg config.Config, svcs *app.Services, introspector 
auth.Introspector)
        
processctl.NewJobSubmissionTaskController(svcs.JobSubmissionTask).Register(mux)
        
processctl.NewJobMonitoringTaskController(svcs.JobMonitoringTask).Register(mux)
        
processctl.NewInteractiveCommandTaskController(svcs.InteractiveCommandTask).Register(mux)
+       processctl.NewLinkController(svcs.Link).Register(mux)
 
        mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ 
*http.Request) {
                httpx.WriteJSON(w, http.StatusOK, map[string]string{"status": 
"UP"})
@@ -124,7 +125,7 @@ func cors(allowed []string) func(http.Handler) http.Handler 
{
                        if origin != "" && (allowAll || origins[origin]) {
                                
w.Header().Set("Access-Control-Allow-Credentials", "true")
                                w.Header().Set("Access-Control-Allow-Headers", 
"Authorization, Content-Type")
-                               w.Header().Set("Access-Control-Allow-Methods", 
"GET, POST, PUT, DELETE, OPTIONS")
+                               w.Header().Set("Access-Control-Allow-Methods", 
"GET, POST, PUT, PATCH, DELETE, OPTIONS")
                        }
 
                        if r.Method == http.MethodOptions {
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
index 4d5ee9314e..529ff267d6 100644
--- a/internal/server/server_test.go
+++ b/internal/server/server_test.go
@@ -109,7 +109,7 @@ func newHarness(t *testing.T) *harness {
                }
        }
 
-       cfg := config.Config{CORSAllowedOrigins: []string{"*"}}
+       cfg := config.Config{CORSAllowedOrigins: []string{"*"}, PublicURL: 
"https://airavata.example.org"}
        introspector := stubIntrospector{
                tokenAdmin: {Name: "admin-user", Authorities: 
[]string{string(role.Admin)}},
                tokenAlice: {Name: "alice", Authorities: 
[]string{string(role.User)}},
diff --git a/website/sidebars.js b/website/sidebars.js
index 00a43d7f71..ed5db6d3e3 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -8,7 +8,7 @@ const sidebars = {
       type: 'category',
       label: 'Concepts',
       collapsed: false,
-      items: ['application', 'data-product', 'virtual-data', 'batch-clusters'],
+      items: ['application', 'data-product', 'virtual-data', 'batch-clusters', 
'notebooks'],
     },
     {
       type: 'category',

Reply via email to