jupyterWebForwardingURL builds the URL to open for the forwarded JupyterLab port. The origin comes from the tunnel's own web forwarding URI. The codespace supplies only the path, query and fragment, which carry the JupyterLab auth token. The codespace is untrusted here: it reports both the port and
(ctx context.Context, fwd portforwarder.PortForwarder, serverPort int, serverURL string)
| 127 | // URL that is reachable without the private-port authentication gate. The check reflects the |
| 128 | // port's visibility at the moment the URL is built and does not constrain it afterwards. |
| 129 | func jupyterWebForwardingURL(ctx context.Context, fwd portforwarder.PortForwarder, serverPort int, serverURL string) (string, error) { |
| 130 | ports, err := fwd.ListPorts(ctx) |
| 131 | if err != nil { |
| 132 | return "", fmt.Errorf("failed to list forwarded ports: %w", err) |
| 133 | } |
| 134 | |
| 135 | var forwardingURI string |
| 136 | for _, port := range ports { |
| 137 | if int(port.PortNumber) != serverPort { |
| 138 | continue |
| 139 | } |
| 140 | var entries []tunnels.TunnelAccessControlEntry |
| 141 | if port.AccessControl != nil { |
| 142 | entries = port.AccessControl.Entries |
| 143 | } |
| 144 | if visibility := portforwarder.AccessControlEntriesToVisibility(entries); visibility != portforwarder.PrivatePortVisibility { |
| 145 | return "", fmt.Errorf("JupyterLab port %d is %s rather than private, so it was not opened. Set the port to private and try again", serverPort, visibility) |
| 146 | } |
| 147 | if len(port.PortForwardingURIs) > 0 { |
| 148 | forwardingURI = port.PortForwardingURIs[0] |
| 149 | } |
| 150 | break |
| 151 | } |
| 152 | |
| 153 | if forwardingURI == "" { |
| 154 | return "", fmt.Errorf("no web forwarding URL available for JupyterLab port %d", serverPort) |
| 155 | } |
| 156 | |
| 157 | base, err := url.Parse(forwardingURI) |
| 158 | if err != nil { |
| 159 | return "", fmt.Errorf("failed to parse web forwarding URL: %w", err) |
| 160 | } |
| 161 | |
| 162 | reported, err := url.Parse(serverURL) |
| 163 | if err != nil { |
| 164 | return "", fmt.Errorf("failed to parse JupyterLab server URL: %w", err) |
| 165 | } |
| 166 | |
| 167 | // Resolving a reference keeps the forwarding URI's scheme and host while taking the |
| 168 | // path, query and fragment from the reported URL. |
| 169 | target := base.ResolveReference(&url.URL{ |
| 170 | Path: reported.Path, |
| 171 | RawQuery: reported.RawQuery, |
| 172 | Fragment: reported.Fragment, |
| 173 | }) |
| 174 | |
| 175 | return target.String(), nil |
| 176 | } |