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

DImuthuUpe pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata.git


The following commit(s) were added to refs/heads/master by this push:
     new 489d1a8200 Store SSH passwords (#751)
489d1a8200 is described below

commit 489d1a82007f053e45ffca1d6c309cf3590240c6
Author: Yasith Jayawardana <[email protected]>
AuthorDate: Mon Nov 9 06:19:46 2026 -0500

    Store SSH passwords (#751)
---
 api/credentials/dto/ssh_credential.go              |  1 +
 api/credentials/model/ssh_credential.go            |  1 +
 api/credentials/service/service.go                 |  4 ++
 docs/api.md                                        |  1 +
 docs/interactive-auth.md                           |  5 +-
 docs/openapi.yaml                                  |  5 +-
 .../db/migrations/0012_ssh_credential_password.sql |  5 ++
 internal/mcp/client/client.gen.go                  |  5 +-
 internal/server/server_test.go                     |  6 ++
 internal/ssh/ssh.go                                | 17 +++++-
 internal/ssh/ssh_test.go                           | 65 ++++++++++++++++++++++
 11 files changed, 109 insertions(+), 6 deletions(-)

diff --git a/api/credentials/dto/ssh_credential.go 
b/api/credentials/dto/ssh_credential.go
index bd634e3137..16b87c2012 100644
--- a/api/credentials/dto/ssh_credential.go
+++ b/api/credentials/dto/ssh_credential.go
@@ -38,6 +38,7 @@ type SSHCredentialRequest struct {
        PublicKey         string  `json:"publicKey"`
        PrivateKey        *string `json:"privateKey"`
        Passphrase        *string `json:"passphrase"`
+       Password          *string `json:"password"`
        FullInteractive   bool    `json:"fullInteractive"`
 }
 
diff --git a/api/credentials/model/ssh_credential.go 
b/api/credentials/model/ssh_credential.go
index 7beb19b9b5..07b4f0232b 100644
--- a/api/credentials/model/ssh_credential.go
+++ b/api/credentials/model/ssh_credential.go
@@ -47,6 +47,7 @@ type SSHCredential struct {
        PublicKey  string  `gorm:"column:public_key;type:text;not null" 
json:"publicKey"`
        PrivateKey string  `gorm:"column:private_key;type:text;not null" 
json:"-"`
        Passphrase *string `gorm:"column:passphrase;type:varchar(255)" json:"-"`
+       Password   *string `gorm:"column:password;type:varchar(255)" json:"-"`
 
        // Certificate based authentication. This indicates whether the SSH 
credential uses a certificate for authentication.
        IsCertificate bool `gorm:"column:is_certificate;not null" 
json:"isCertificate"`
diff --git a/api/credentials/service/service.go 
b/api/credentials/service/service.go
index cdc824db2b..bcea2874ae 100644
--- a/api/credentials/service/service.go
+++ b/api/credentials/service/service.go
@@ -171,6 +171,7 @@ func (s *SSHCredentialService) Create(ctx context.Context, 
req *dto.SSHCredentia
                PublicKey:         req.PublicKey,
                PrivateKey:        ptr.From(req.PrivateKey),
                Passphrase:        ptr.NonBlank(req.Passphrase),
+               Password:          ptr.NonBlank(req.Password),
                FullInteractive:   req.FullInteractive,
                OwnerID:           owner.ID,
        }
@@ -201,6 +202,9 @@ func (s *SSHCredentialService) Update(ctx context.Context, 
id string, req *dto.S
        if v := ptr.NonBlank(req.Passphrase); v != nil {
                key.Passphrase = v
        }
+       if v := ptr.NonBlank(req.Password); v != nil {
+               key.Password = v
+       }
 
        if err := s.keys.Save(ctx, key); err != nil {
                return nil, err
diff --git a/docs/api.md b/docs/api.md
index 8176f9a565..62ea624e59 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -97,6 +97,7 @@ echo "$SSH_CREDENTIAL_ID"
 | `publicKey` | string | required, cannot be blank |
 | `privateKey` | string \| null | required on create; omit on update to keep 
the stored secret |
 | `passphrase` | string \| null | optional |
+| `password` | string \| null | optional, write-only; answers the login's 
password prompt; ignored unless `fullInteractive` |
 | `fullInteractive` | boolean | optional, default `false`; also answer 
keyboard-interactive prompts (OTP, Duo) after the key |
 
 ```json
diff --git a/docs/interactive-auth.md b/docs/interactive-auth.md
index 452b29677f..c4812bebf8 100644
--- a/docs/interactive-auth.md
+++ b/docs/interactive-auth.md
@@ -13,6 +13,7 @@ Interactive authentication is a property of an [SSH 
credential](api.md#ssh-crede
 | Field | Meaning |
 |---|---|
 | `privateKey`, `publicKey`, `passphrase` | The key pair. Airavata always 
offers it first. |
+| `password` | Optional, write-only. Answers the host's first lone password 
prompt, so you are not asked for it. Ignored unless `fullInteractive`. |
 | `fullInteractive` | `true` if the host **also** asks keyboard-interactive 
questions (password, OTP, Duo) after the key. Default `false`. |
 
 In the dashboard, this is the checkbox **"Host also asks keyboard-interactive 
questions (password, OTP, Duo) — answer them from this dashboard"** when you 
register a credential.
@@ -41,7 +42,7 @@ When the login starts, Airavata:
 2. If the host asks keyboard-interactive questions or a password, creates an 
**interactive auth**. This records the host, login user, credential, the host's 
banner and the prompts. The login then waits.
 3. Waits for that user to answer, sends the answers to the host, and lets the 
login proceed.
 
-If the host asks again, for example a Duo prompt after the password, that is a 
**new** interactive auth with a new id.
+If the host asks again, for example a Duo prompt after the password, that is a 
**new** interactive auth with a new id. A stored `password` answers the first 
password prompt itself; every other prompt, such as a Duo passcode, still goes 
to the user.
 
 ### Answer once per login
 
@@ -75,7 +76,7 @@ An authenticated connection is kept and reused by every 
operation that logs in w
 
 The answer is one response per prompt, in order: `{"responses": 
["<password>"]}`. You can instead send `{"cancel": true}` to fail the login 
immediately rather than leave it waiting.
 
-Answers go straight to the SSH handshake. They are **not logged or stored**.
+Answers go straight to the SSH handshake. They are **not logged or stored**. A 
credential's `password` is stored, write-only, and never returned; see 
[api.md](api.md#ssh-credentials).
 
 An auth exists only while its login is waiting. It disappears once it is 
answered or the login gives up. Only the user it was raised for can see or 
answer it. Admins cannot see other users' auths either.
 
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index d570c2449e..f372c7f901 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -3375,6 +3375,9 @@ components:
         passphrase:
           type: [string, "null"]
           description: Write-only. Never returned by any read endpoint.
+        password:
+          type: [string, "null"]
+          description: Write-only. Never returned by any read endpoint.
         fullInteractive:
           type: boolean
           description: Also answer keyboard-interactive prompts (OTP, Duo) 
after the key.
@@ -3383,7 +3386,7 @@ components:
     SSHCredentialResponse:
       type: object
       description: |
-        The read model for a credential. It has no private key or passphrase 
field at all —
+        The read model for a credential. It has no private key, passphrase or 
password field at all —
         the secrets cannot leak through this endpoint because there is nowhere 
for
         them to go.
       properties:
diff --git a/internal/db/migrations/0012_ssh_credential_password.sql 
b/internal/db/migrations/0012_ssh_credential_password.sql
new file mode 100644
index 0000000000..fbf109e2ec
--- /dev/null
+++ b/internal/db/migrations/0012_ssh_credential_password.sql
@@ -0,0 +1,5 @@
+-- Let an SSH credential store a password for the login's password prompt. The 
DDL is
+-- what AutoMigrate emits for SSHCredential.Password — see
+-- TestBaselineMigrationMatchesAutoMigrate.
+
+ALTER TABLE "ssh_credentials" ADD COLUMN "password" varchar(255);
diff --git a/internal/mcp/client/client.gen.go 
b/internal/mcp/client/client.gen.go
index e1b127f7d8..56da9fc5a1 100644
--- a/internal/mcp/client/client.gen.go
+++ b/internal/mcp/client/client.gen.go
@@ -1052,13 +1052,16 @@ type SSHCredentialRequest struct {
        // Passphrase Write-only. Never returned by any read endpoint.
        Passphrase *string `json:"passphrase,omitempty"`
 
+       // Password Write-only. Never returned by any read endpoint.
+       Password *string `json:"password,omitempty"`
+
        // PrivateKey Write-only. Never returned by any read endpoint.
        PrivateKey        *string `json:"privateKey,omitempty"`
        PublicKey         string  `json:"publicKey"`
        SshCredentialName string  `json:"sshCredentialName"`
 }
 
-// SSHCredentialResponse The read model for a credential. It has no private 
key or passphrase field at all —
+// SSHCredentialResponse The read model for a credential. It has no private 
key, passphrase or password field at all —
 // the secrets cannot leak through this endpoint because there is nowhere for
 // them to go.
 type SSHCredentialResponse struct {
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
index fcfe96488e..4d5ee9314e 100644
--- a/internal/server/server_test.go
+++ b/internal/server/server_test.go
@@ -360,12 +360,18 @@ func 
TestSSHCredentialSecretsAreNeverReturnedAndRequiredOnCreate(t *testing.T) {
                "sshCredentialName": "k", "publicKey": "ssh-ed25519 AAAA", 
"privateKey": "SUPER-SECRET",
                "passphrase": "hunter2",
        }, http.StatusCreated)
+       h.mustDo(http.MethodPost, "/api/v1/ssh-credentials", tokenAdmin, 
map[string]any{
+               "sshCredentialName": "p", "password": "letmein-pw", 
"fullInteractive": true,
+       }, http.StatusCreated)
 
        for _, path := range []string{"/api/v1/ssh-credentials", 
"/api/v1/ssh-credentials/" + created["sshCredentialId"].(string)} {
                body := h.do(http.MethodGet, path, tokenAdmin, 
nil).Body.String()
                if strings.Contains(body, "SUPER-SECRET") || 
strings.Contains(body, "hunter2") {
                        t.Errorf("GET %s leaked a secret: %s", path, body)
                }
+               if strings.Contains(body, "letmein-pw") {
+                       t.Errorf("GET %s leaked the password: %s", path, body)
+               }
        }
 }
 
diff --git a/internal/ssh/ssh.go b/internal/ssh/ssh.go
index 5882cd26ad..f91b4af7ea 100644
--- a/internal/ssh/ssh.go
+++ b/internal/ssh/ssh.go
@@ -31,6 +31,7 @@ import (
        "net"
        "os"
        "path/filepath"
+       "regexp"
        "strconv"
        "strings"
        "time"
@@ -52,6 +53,9 @@ const scpOK = 0x00
 // attempt quickly rather than hold a worker slot until the OS gives up on the 
socket.
 const scpDialTimeout = 30 * time.Second
 
+// The host's own password prompt, not an OTP or passcode that also says 
"password".
+var passwordPrompt = regexp.MustCompile(`(?i)^(\S+'s )?password:\s*$`)
+
 type FileMetadata struct {
        Path string
        Size int64
@@ -127,6 +131,15 @@ func newSSHClient(ctx context.Context, dialConfig 
SSHDialConfig, sshContext *Glo
                authMethods = append(authMethods, gossh.PublicKeys(signer))
        }
 
+       // The stored password answers the first lone password prompt; any 
other prompt goes to the user.
+       stored := dialConfig.cred.Password
+       ask := func(name, instruction string, prompts []Prompt) ([]string, 
error) {
+               if answer := stored; answer != nil && len(prompts) == 1 && 
!prompts[0].Echo && passwordPrompt.MatchString(prompts[0].Text) {
+                       stored = nil
+                       return []string{*answer}, nil
+               }
+               return askUserInteractive(ctx, dialConfig, sshContext, banner, 
name, instruction, prompts)
+       }
        if dialConfig.cred.FullInteractive {
                ki := gossh.KeyboardInteractive(func(name, instruction string, 
questions []string, echos []bool) ([]string, error) {
                        // RFC 4256 allows an INFO_REQUEST with zero prompts 
(servers use it to
@@ -140,7 +153,7 @@ func newSSHClient(ctx context.Context, dialConfig 
SSHDialConfig, sshContext *Glo
                                return []string{}, nil
                        }
 
-                       answers, err := askUserInteractive(ctx, dialConfig, 
sshContext, banner, name, instruction, prompts)
+                       answers, err := ask(name, instruction, prompts)
                        if err != nil {
                                return nil, err
                        }
@@ -154,7 +167,7 @@ func newSSHClient(ctx context.Context, dialConfig 
SSHDialConfig, sshContext *Glo
                // The server only tries it if it advertises the method.
                password := gossh.PasswordCallback(func() (string, error) {
                        prompt := fmt.Sprintf("%s@%s's password: ", 
dialConfig.sshUsername, dialConfig.host)
-                       answers, err := askUserInteractive(ctx, dialConfig, 
sshContext, banner, "", "", []Prompt{{Text: prompt, Echo: false}})
+                       answers, err := ask("", "", []Prompt{{Text: prompt, 
Echo: false}})
                        if err != nil {
                                return "", err
                        }
diff --git a/internal/ssh/ssh_test.go b/internal/ssh/ssh_test.go
index d2f2b05771..f2aee37f5c 100644
--- a/internal/ssh/ssh_test.go
+++ b/internal/ssh/ssh_test.go
@@ -21,11 +21,17 @@
 package ssh
 
 import (
+       "context"
+       "crypto/ed25519"
+       "crypto/rand"
+       "errors"
+       "net"
        "os"
        "testing"
        "time"
 
        credmodel "github.com/apache/airavata/api/credentials/model"
+       gossh "golang.org/x/crypto/ssh"
 )
 
 // Test this individually
@@ -153,3 +159,62 @@ func TestSCPUpload(t *testing.T) {
        }
        t.Logf("SCP file metadata: %+v", metadata)
 }
+
+// sshServer serves config and closes each connection after grace, like sshd's 
LoginGraceTime.
+func sshServer(t *testing.T, config *gossh.ServerConfig, grace time.Duration) 
SSHDialConfig {
+       _, private, _ := ed25519.GenerateKey(rand.Reader)
+       signer, _ := gossh.NewSignerFromKey(private)
+       config.AddHostKey(signer)
+       listener, err := net.Listen("tcp", "127.0.0.1:0")
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(func() { listener.Close() })
+       go func() {
+               for conn, err := listener.Accept(); err == nil; conn, err = 
listener.Accept() {
+                       time.AfterFunc(grace, func() { conn.Close() })
+                       go serveNoChannels(conn, config)
+               }
+       }()
+       return NewSSHDialConfig("127.0.0.1", 
listener.Addr().(*net.TCPAddr).Port, "alice", credmodel.SSHCredential{ID: "c1", 
FullInteractive: true}, "alice")
+}
+
+func TestStoredPasswordLeavesOnlyFurtherPromptsToTheUser(t *testing.T) {
+       password := "stored-pw"
+       answers := map[string]string{"One-time password: ": "654321", 
"Password: ": password, "Passcode: ": "123456"}
+       dial, sshContext := sshServer(t, 
&gossh.ServerConfig{KeyboardInteractiveCallback: func(_ gossh.ConnMetadata, ask 
gossh.KeyboardInteractiveChallenge) (*gossh.Permissions, error) {
+               for _, prompt := range []string{"One-time password: ", 
"Password: ", "Passcode: "} {
+                       if got, err := ask("", "", []string{prompt}, 
[]bool{false}); err != nil || got[0] != answers[prompt] {
+                               return nil, errors.New("refused")
+                       }
+               }
+               return nil, nil
+       }}, time.Minute), NewGlobalSSHContext()
+       dial.cred.Password = &password
+       t.Cleanup(sshContext.ConnectionPool.Close)
+       done := make(chan error, 1)
+       go func() {
+               _, err := dialSSH(context.Background(), dial, sshContext)
+               done <- err
+       }()
+
+       var asked []string
+       for pending, changed := 
sshContext.InteractiveAuthStore.NextAuthForUser("alice"); ; pending, changed = 
sshContext.InteractiveAuthStore.NextAuthForUser("alice") {
+               if pending != nil {
+                       prompts, _ := pending.Read()
+                       asked = append(asked, prompts[0].Text)
+                       _ = 
pending.SetResponse([]string{answers[prompts[0].Text]}, nil)
+                       continue
+               }
+               select {
+               case <-changed:
+               case err := <-done:
+                       if err != nil || len(asked) != 2 || asked[0] != 
"One-time password: " || asked[1] != "Passcode: " {
+                               t.Fatalf("login: %v; the user was asked %q, 
want only the one-time password and the passcode", err, asked)
+                       }
+                       return
+               case <-time.After(5 * time.Second):
+                       t.Fatal("the login neither prompted nor finished")
+               }
+       }
+}

Reply via email to