Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 54 additions & 1 deletion languages/golang/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,33 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.

### Added

- **You choose where `OIDCFederation` and
`OIDCFederationWithDetectedWorkspace` get their client key** (#1723).
Call `WithClientKey` on the credentials with a `ClientKeySource`:
- `ClientKeyFromEnv()` reads `CS_CLIENT_ID` and `CS_CLIENT_KEY`.
- `ClientKeyFromProfile(crn)` reads the key `stash auth login` saved for
the workspace `crn` names.
- `ClientKeyFromValues(clientID, key)` takes a key your program loaded.

Each source reads only its own place. `NewClient` still creates the
federation strategy, and `Client.Close` still releases it.
`NewClient` refuses a `ClientKeyFromProfile` source for another workspace
than the federation's with `auth.ErrConfig`.

```go
creds := encrypt.OIDCFederation(cfg.WorkspaceCRN, provider).
WithClientKey(encrypt.ClientKeyFromValues(cfg.ClientID, encrypt.NewClientKey([]byte(cfg.ClientKey))))
```

- **`auth.CRN`, a parsed workspace CRN.** `auth.ProfileStore.ParseCRN`
parses text with the parser the Rust strategies use. The `CRN` gives the
region, the workspace id, and the service name, if there is one. Text
that is not a workspace CRN is `auth.ErrConfig`.
- **`auth.ProfileStore.WorkspaceStoreForCRN`** returns the store of the
workspace a `CRN` names, whichever workspace is current.
- **`auth.ProfileStore.DetectWorkspaceCRN`** returns the workspace that
`OIDCWithDetectedWorkspace` federates into, as a `CRN`.

- `gensupport.UUID`, the kind `"uuid"`: a field the engine seals and
opens as a UUID, sixteen bytes under vitaminc's UUID logical type. It
takes an equality index and no order or match index. Its value is a
Expand All @@ -37,6 +64,29 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.

### Breaking

- **`OIDCFederation` no longer reads `CS_CLIENT_ID` and `CS_CLIENT_KEY`.**
Its client key now comes only from the profile: the key `stash auth
login` saved for the workspace its CRN names. It used to read the two
variables first. If neither was set, it read the key of the CLI's
current workspace. That could be a different workspace from the tokens',
and then ZeroKMS refused every request. If this machine has no key for
the named workspace, `NewClient` returns `ErrNoCredentials`. To keep
reading the variables, choose the source:

```go
creds := encrypt.OIDCFederation(crn, provider).WithClientKey(encrypt.ClientKeyFromEnv())
```

`AutoCredentials` is unchanged: it still reads the variables, then the
CLI's current workspace.

- **`OIDCFederation` returns `*encrypt.OIDCFederationCredentials`, not
`encrypt.Credentials`.** The new type implements `Credentials`, so
`encrypt.WithCredentials(encrypt.OIDCFederation(...))` still builds. Code
that assigns the result to a variable and later assigns other credentials
to that variable stops building. Declare the variable as
`encrypt.Credentials`.

- **`Match` refuses `vars` that are not a JSON object with the reason
`json_vars_not_object`, not `json_input`** (#1987). If your program
compares `Reason()` with `json_input` for this case, change it to the
Expand Down Expand Up @@ -238,7 +288,10 @@ installed rc.6's bundle, you do not need to run it again.
`CS_WORKSPACE_CRN` that is not a CRN is an error, and the profile is not
read. With neither, the error says to set `CS_WORKSPACE_CRN` or run
`stash auth login`. `OIDCFederation` and `OIDC` with a named CRN work as
before. (#1724)
before. (#1724) The client key of
`encrypt.OIDCFederationWithDetectedWorkspace` is the detected workspace's
key in the profile. It returns `*encrypt.OIDCFederationCredentials`, so
`WithClientKey` chooses another source.

### Breaking

Expand Down
12 changes: 12 additions & 0 deletions languages/golang/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ the cross-process lock a device-session refresh holds with the `stash` CLI
(the IdP revokes a whole refresh-token chain when one is used twice).
`workspace.Token(ctx)` still reads the stored token, for inspection.

`profile.ParseCRN(ctx, text)` parses a workspace CRN into an `auth.CRN`,
with the parser the Rust strategies use. The `CRN` gives the region, the
workspace id, and the service name, if there is one.

`profile.WorkspaceStoreForCRN(ctx, crn)` is the store of the workspace a
`CRN` names, whichever workspace is current. Read the client key there when
the tokens are for that workspace, as an OIDC strategy's are. An `encrypt`
client reads the same key with `encrypt.ClientKeyFromProfile(crn)`. The
client then owns the profile and the strategy.

With no profile directory at all (CI, a container, a server authenticating
by federation), `auth.OpenWithoutProfile(ctx)` runs the guest with
nothing mounted: the access-key and OIDC strategies work, and every profile
Expand All @@ -91,6 +101,8 @@ session `stash auth login` saved for the CLI's current workspace. A
read. With neither, the error is `ErrNotAuthenticated`. A saved session that
cannot be read is reported as itself, never as not logged in. Call it on the
profile root: a workspace store has no current workspace, and is `ErrConfig`.
`profile.DetectWorkspaceCRN(ctx)` returns the `CRN` it detects, so you can
read other data of the same workspace, such as its client key.
The OIDC provider is a one-method `Token(context.Context) (string, error)`
interface, called on every token fetch for the JWT of the user the call is
for; each distinct JWT is exchanged once while its CTS token lasts. Use
Expand Down
32 changes: 32 additions & 0 deletions languages/golang/auth/answer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,35 @@ func mustMarshalAuth(t *testing.T, v any) []byte {
}
return out
}

// The answer of sa_auth_validate_crn is an object of the CRN's parts. An
// answer of another shape is ErrInternal, and the error names the export
// and the field.
func TestCRNAnswerNamesTheExportAndTheField(t *testing.T) {
marshal := func(v any) []byte {
out, err := vcffi.Marshal(v)
if err != nil {
t.Fatal(err)
}
return out
}
for _, tc := range []struct {
answer []byte
want string
}{
{[]byte{0xff}, "cannot read the guest's answer from sa_auth_validate_crn: "},
{marshal("crn"), "from sa_auth_validate_crn: it is a string, not an object"},
{marshal(vcvalue.Object{{Key: "workspace_id", Value: "ws"}}), "from sa_auth_validate_crn: it has no region"},
{marshal(vcvalue.Object{{Key: "region", Value: "r"}, {Key: "workspace_id", Value: int64(1)}}), "from sa_auth_validate_crn: workspace_id is a number, not a string"},
{marshal(vcvalue.Object{{Key: "region", Value: ""}, {Key: "workspace_id", Value: "ws"}}), "from sa_auth_validate_crn: it has an empty region or workspace id"},
} {
crn, err := crnParts(tc.answer)
if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), tc.want) || !crn.IsZero() {
t.Errorf("%v, %v, want %q", crn, err, tc.want)
}
}
crn, err := crnParts(marshal(vcvalue.Object{{Key: "region", Value: "r"}, {Key: "workspace_id", Value: "ws"}, {Key: "service_name", Value: nil}}))
if err != nil || crn.String() != "crn:r:ws" {
t.Errorf("a good answer: %v, %v", crn, err)
}
}
96 changes: 96 additions & 0 deletions languages/golang/auth/crn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package auth

import (
"context"
"fmt"

"github.com/cipherstash/stack/languages/golang/internal/guest"
"github.com/tetratelabs/wazero/api"
)

// CRN is a parsed workspace CRN (CipherStash resource name). A CRN has the
// workspace's region, the workspace's id, and an optional service name.
// The text form is crn:<region>:<workspace id>, with :<service name>
// after it when there is one.
//
// Get a CRN from [ProfileStore.ParseCRN]. The zero CRN names no workspace.
type CRN struct {
region string
workspaceID string
serviceName string
}

// ParseCRN parses text as a workspace CRN. The guest parses it with the
// same parser that stack-auth's strategies use, so a CRN that ParseCRN
// accepts is one they accept.
//
// Text that is not a workspace CRN is [ErrConfig]. ParseCRN reads no
// profile data, so it works on a store from [OpenWithoutProfile] too.
func (s *ProfileStore) ParseCRN(ctx context.Context, text string) (CRN, error) {
out, err := s.callArgs(ctx, func(i *instance) api.Function { return i.authValidateCRN }, guest.BufArg([]byte(text)))
if err != nil {
return CRN{}, err
}
return crnParts(out)
}

// crnParts reads the answer of sa_auth_validate_crn.
func crnParts(out []byte) (CRN, error) {
fields, err := object("sa_auth_validate_crn", out)
if err != nil {
return CRN{}, err
}
var c CRN
if c.region, err = fields.text("region"); err != nil {
return CRN{}, err
}
if c.workspaceID, err = fields.text("workspace_id"); err != nil {
return CRN{}, err
}
if c.serviceName, err = fields.optionalText("service_name"); err != nil {
return CRN{}, err
}
if c.region == "" || c.workspaceID == "" {
return CRN{}, fields.refuse("it has an empty region or workspace id")
}
return c, nil
}

// Region is the region the workspace is in, such as ap-southeast-2.aws.
func (c CRN) Region() string { return c.region }

// WorkspaceID is the id of the workspace.
func (c CRN) WorkspaceID() string { return c.workspaceID }

// ServiceName is the CRN's service name, or "" when it has none.
func (c CRN) ServiceName() string { return c.serviceName }

// IsZero reports whether c is the zero CRN, which names no workspace.
func (c CRN) IsZero() bool { return c == CRN{} }

// String is the CRN's text form. The zero CRN is "".
func (c CRN) String() string {
if c.IsZero() {
return ""
}
text := "crn:" + c.region + ":" + c.workspaceID
if c.serviceName != "" {
text += ":" + c.serviceName
}
return text
}

// WorkspaceStoreForCRN is [ProfileStore.WorkspaceStore] for the workspace
// that crn names. WorkspaceStoreForCRN never returns the current
// workspace's store in its place.
//
// The store does not need profile data on this machine. If there is none
// for the workspace, reads from the store report [ErrNotFound]. On a store
// from [OpenWithoutProfile] it reports [ErrNoProfile]. The zero CRN is
// [ErrConfig].
func (s *ProfileStore) WorkspaceStoreForCRN(ctx context.Context, crn CRN) (*ProfileStore, error) {
if crn.IsZero() {
return nil, fmt.Errorf("%w: the CRN is the zero CRN, which names no workspace", ErrConfig)
}
return s.WorkspaceStore(ctx, crn.workspaceID)
}
30 changes: 30 additions & 0 deletions languages/golang/auth/detect_workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,33 @@ func TestOIDCWithDetectedWorkspaceRefusesAWorkspaceStore(t *testing.T) {
}
}
}

// DetectWorkspaceCRN is the workspace OIDCWithDetectedWorkspace federates
// into: the variable when it is set, else the saved session's. A workspace
// store has no current workspace to detect from.
func TestDetectWorkspaceCRNIsTheFederationWorkspace(t *testing.T) {
guestOrSkip(t)
ctx := context.Background()
profile := openProfile(t, loggedInProfile(t, sessionJSON(t, "ap-southeast-2.aws")))
unsetEnv(t, "CS_WORKSPACE_CRN")
crn, err := profile.DetectWorkspaceCRN(ctx)
if err != nil || crn.String() != testSessionCRN || crn.WorkspaceID() != wsA {
t.Fatalf("from the session: %v, %v; want %s", crn, err, testSessionCRN)
}
t.Setenv("CS_WORKSPACE_CRN", testCRN)
crn, err = profile.DetectWorkspaceCRN(ctx)
if err != nil || crn.String() != testCRN {
t.Fatalf("from the variable: %v, %v; want %s", crn, err, testCRN)
}
t.Setenv("CS_WORKSPACE_CRN", "not-a-crn")
if crn, err := profile.DetectWorkspaceCRN(ctx); !errors.Is(err, ErrConfig) || !crn.IsZero() {
t.Fatalf("a bad variable: %v, %v; want ErrConfig", crn, err)
}
ws, err := profile.WorkspaceStore(ctx, wsA)
if err != nil {
t.Fatal(err)
}
if _, err := ws.DetectWorkspaceCRN(ctx); !errors.Is(err, ErrConfig) {
t.Fatalf("on a workspace store: %v, want ErrConfig", err)
}
}
3 changes: 2 additions & 1 deletion languages/golang/auth/guest/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,8 @@ pub unsafe extern "C" fn sa_auth_new(ptr: *const u8, len: u32) -> u64 {
export1(ptr, len, auth::create)
}

/// Validate a workspace CRN using the same Rust parser as AutoStrategy.
/// Validate a workspace CRN using the same Rust parser as AutoStrategy, and
/// return its parts: the region, the workspace id, and the service name.
/// # Safety
/// The input pair is validated against guest linear memory.
#[no_mangle]
Expand Down
26 changes: 24 additions & 2 deletions languages/golang/auth/guest/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,32 @@ fn parse_base_url(value: Option<String>) -> Result<Option<url::Url>, u32> {
.transpose()
}

/// Parses a workspace CRN with the parser `AutoStrategy` uses. The output is
/// a codec object of the CRN's parts:
/// `{"region": text, "workspace_id": text, "service_name": text or null}`.
pub fn validate_crn(bytes: &[u8]) -> Result<Vec<u8>, u32> {
let text = std::str::from_utf8(bytes).map_err(|_| malformed("the CRN is not UTF-8"))?;
let _: Crn = text.parse().map_err(|e| fail_auth(&AuthError::from(e)))?;
Ok(Vec::new())
let crn: Crn = text.parse().map_err(|e| fail_auth(&AuthError::from(e)))?;
crn_parts(&crn)
.encode()
.map_err(|_| internal("a CRN's parts could not be encoded"))
}

/// The parts of `crn`, as `validate_crn` returns them.
fn crn_parts(crn: &Crn) -> HostValue {
HostValue::Map(vec![
("region".to_owned(), HostValue::text(crn.region.to_string())),
(
"workspace_id".to_owned(),
HostValue::text(crn.workspace_id.to_string()),
),
(
"service_name".to_owned(),
crn.service_name
.as_deref()
.map_or(HostValue::Null, HostValue::text),
),
])
}

// A CRN or access key that does not parse is a configuration error, the
Expand Down
Loading
Loading