issue-creds 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- issue_creds/__init__.py +8 -0
- issue_creds/cli.py +137 -0
- issue_creds/core.py +142 -0
- issue_creds/errors.py +9 -0
- issue_creds/models.py +20 -0
- issue_creds/output.py +68 -0
- issue_creds/policies.py +91 -0
- issue_creds-0.1.0.dist-info/METADATA +86 -0
- issue_creds-0.1.0.dist-info/RECORD +12 -0
- issue_creds-0.1.0.dist-info/WHEEL +4 -0
- issue_creds-0.1.0.dist-info/entry_points.txt +2 -0
- issue_creds-0.1.0.dist-info/licenses/LICENSE +201 -0
issue_creds/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""issue-creds: scope-limited, short-lived AWS S3 credential vending for JupyterHub."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("issue-creds")
|
|
7
|
+
except PackageNotFoundError: # not installed (e.g. running from a bare checkout)
|
|
8
|
+
__version__ = "unknown"
|
issue_creds/cli.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Typer CLI: the thin presentation layer over the issue_creds package."""
|
|
2
|
+
|
|
3
|
+
# NB: this module intentionally omits `from __future__ import annotations`.
|
|
4
|
+
# Typer introspects this command's annotations at runtime (get_type_hints) to
|
|
5
|
+
# build the CLI, so they must stay as real objects, not strings — older Typer
|
|
6
|
+
# releases mis-detected stringized annotations and turned required options into
|
|
7
|
+
# positional arguments.
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from typing import Annotated
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
|
|
15
|
+
from . import __version__, core, output, policies
|
|
16
|
+
from .errors import CredsError
|
|
17
|
+
from .models import OutputFormat, Role
|
|
18
|
+
|
|
19
|
+
app = typer.Typer(
|
|
20
|
+
add_completion=False,
|
|
21
|
+
help="Vend short-lived, scope-limited AWS credentials for S3.",
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _version_cb(value: bool) -> None:
|
|
26
|
+
"""Eager --version callback: print the version and exit before anything else."""
|
|
27
|
+
if value:
|
|
28
|
+
typer.echo(__version__)
|
|
29
|
+
raise typer.Exit()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _parse_lifetime(value: str) -> int:
|
|
33
|
+
"""Parse a --lifetime string to seconds, as a clean Typer parameter error."""
|
|
34
|
+
try:
|
|
35
|
+
return core.parse_duration(value)
|
|
36
|
+
except ValueError as exc:
|
|
37
|
+
raise typer.BadParameter(str(exc)) from exc
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@app.command()
|
|
41
|
+
def main(
|
|
42
|
+
role: Annotated[Role, typer.Option(
|
|
43
|
+
"--role", help="Permission profile to request.")],
|
|
44
|
+
bucket_scope: Annotated[str, typer.Option(
|
|
45
|
+
"--bucket-scope",
|
|
46
|
+
help="Target S3 bucket name (no arn:/s3:// prefix).",
|
|
47
|
+
)] = "reflective-persistent-prod",
|
|
48
|
+
prefix: Annotated[str | None, typer.Option(
|
|
49
|
+
"--prefix",
|
|
50
|
+
help="Restrict to a key prefix, e.g. 'lagranto/runs'. For downloads it "
|
|
51
|
+
"is optional (whole bucket if omitted). For uploads it overrides "
|
|
52
|
+
"the default JUPYTERHUB_USER namespace.")] = None,
|
|
53
|
+
lifetime: Annotated[str, typer.Option(
|
|
54
|
+
"--lifetime",
|
|
55
|
+
help="Credential lifetime: '30m', '2h', '1h30m', or seconds.")] = "30m",
|
|
56
|
+
fmt: Annotated[OutputFormat, typer.Option(
|
|
57
|
+
"--format", help="Output format.")] = OutputFormat.env,
|
|
58
|
+
profile_name: Annotated[str, typer.Option(
|
|
59
|
+
"--profile-name",
|
|
60
|
+
help="Profile name for --format profile.")] = "s3-scoped",
|
|
61
|
+
region: Annotated[str | None, typer.Option(
|
|
62
|
+
"--region",
|
|
63
|
+
help="Override region (else AWS_REGION/AWS_DEFAULT_REGION).")] = None,
|
|
64
|
+
dry_run: Annotated[bool, typer.Option(
|
|
65
|
+
"--dry-run",
|
|
66
|
+
help="Print the session policy and request params; do not call STS.")] = False,
|
|
67
|
+
version: Annotated[bool, typer.Option(
|
|
68
|
+
"--version", callback=_version_cb, is_eager=True,
|
|
69
|
+
help="Show version and exit.")] = False,
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Issue scoped, short-lived S3 credentials for use outside of the Hub."""
|
|
72
|
+
try:
|
|
73
|
+
seconds = _parse_lifetime(lifetime)
|
|
74
|
+
cap = core.max_duration(role)
|
|
75
|
+
if seconds < core.AWS_MIN_DURATION:
|
|
76
|
+
raise CredsError(
|
|
77
|
+
f"lifetime {seconds}s is below the AWS minimum "
|
|
78
|
+
f"({core.AWS_MIN_DURATION}s / 15m)."
|
|
79
|
+
)
|
|
80
|
+
if seconds > cap:
|
|
81
|
+
raise CredsError(
|
|
82
|
+
f"lifetime {seconds}s exceeds the cap {cap}s."
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
bucket = bucket_scope.removeprefix("s3://").strip("/")
|
|
86
|
+
|
|
87
|
+
if role is Role.upload:
|
|
88
|
+
# Defaults to your own JUPYTERHUB_USER namespace; --prefix overrides it.
|
|
89
|
+
effective_prefix: str | None = (
|
|
90
|
+
prefix if prefix is not None else core.user_prefix()
|
|
91
|
+
)
|
|
92
|
+
elif role is Role.power:
|
|
93
|
+
if prefix is not None:
|
|
94
|
+
raise CredsError(
|
|
95
|
+
"--prefix is not allowed for the power role; it requests the "
|
|
96
|
+
"full role identity policy with no prefix scoping."
|
|
97
|
+
)
|
|
98
|
+
effective_prefix = None
|
|
99
|
+
else:
|
|
100
|
+
effective_prefix = prefix
|
|
101
|
+
|
|
102
|
+
policy = policies.build_policy(role, bucket, effective_prefix)
|
|
103
|
+
region_ = (
|
|
104
|
+
region
|
|
105
|
+
or os.environ.get("AWS_REGION")
|
|
106
|
+
or os.environ.get("AWS_DEFAULT_REGION")
|
|
107
|
+
)
|
|
108
|
+
sess = core.session_name()
|
|
109
|
+
arn = core.role_arn_for(role)
|
|
110
|
+
|
|
111
|
+
if dry_run:
|
|
112
|
+
typer.echo(f"# role : {role.value}")
|
|
113
|
+
typer.echo(f"# role ARN : {arn}")
|
|
114
|
+
typer.echo(f"# session name : {sess}")
|
|
115
|
+
typer.echo(f"# scope prefix : {effective_prefix or '(whole bucket)'}")
|
|
116
|
+
typer.echo(f"# duration (s) : {seconds}")
|
|
117
|
+
typer.echo(f"# region : {region_ or '(unset)'}")
|
|
118
|
+
typer.echo("# session policy :")
|
|
119
|
+
typer.echo(
|
|
120
|
+
json.dumps(policy, indent=2) if policy
|
|
121
|
+
else "# (none — power role uses the full role policy)"
|
|
122
|
+
)
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
token = core.web_identity_token()
|
|
126
|
+
creds = core.assume_role(arn, sess, token, seconds, policy, region_)
|
|
127
|
+
stdout_text, note = output.render(creds, region_, fmt, profile_name)
|
|
128
|
+
typer.echo(stdout_text)
|
|
129
|
+
if note:
|
|
130
|
+
typer.echo(note, err=True)
|
|
131
|
+
except CredsError as exc:
|
|
132
|
+
typer.echo(f"issue-creds: error: {exc}", err=True)
|
|
133
|
+
raise typer.Exit(code=1) from None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
app()
|
issue_creds/core.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Environment resolution, duration parsing, and the STS call.
|
|
2
|
+
|
|
3
|
+
Everything here is CLI-agnostic and raises CredsError for user-facing failures.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import boto3
|
|
14
|
+
from botocore.exceptions import BotoCoreError, ClientError
|
|
15
|
+
|
|
16
|
+
from .errors import CredsError
|
|
17
|
+
from .models import Role
|
|
18
|
+
|
|
19
|
+
# Per-role IAM role ARNs. Each falls back to $AWS_ROLE_ARN so the tool works
|
|
20
|
+
# with a single role (session policy as advisory guardrail) and tightens into
|
|
21
|
+
# real enforcement once dedicated roles exist and these are set.
|
|
22
|
+
_ROLE_ARN_ENV = {
|
|
23
|
+
Role.download: "ISSUE_CREDS_DOWNLOAD_ROLE_ARN",
|
|
24
|
+
Role.upload: "ISSUE_CREDS_UPLOAD_ROLE_ARN",
|
|
25
|
+
Role.power: "ISSUE_CREDS_POWER_ROLE_ARN",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
# AWS hard limits for AssumeRoleWithWebIdentity duration.
|
|
29
|
+
AWS_MIN_DURATION = 900 # 15m
|
|
30
|
+
DEFAULT_MAX_DURATION = 3600 # 1h (download/power); see ISSUE_CREDS_MAX_LIFETIME
|
|
31
|
+
UPLOAD_MAX_DURATION = 21600 # 6h; uploads may run long. Needs the upload role's
|
|
32
|
+
# MaxSessionDuration >= 6h to actually be granted by STS.
|
|
33
|
+
|
|
34
|
+
_DUR_RE = re.compile(r"^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_duration(text: str) -> int:
|
|
38
|
+
"""Accept '30m', '2h', '1h30m', '900s', or bare seconds -> int seconds.
|
|
39
|
+
|
|
40
|
+
Raises ValueError on malformed input (the CLI converts this to a clean
|
|
41
|
+
parameter error).
|
|
42
|
+
"""
|
|
43
|
+
s = text.strip().lower()
|
|
44
|
+
if s.isdigit():
|
|
45
|
+
return int(s)
|
|
46
|
+
m = _DUR_RE.match(s)
|
|
47
|
+
if not m or not any(m.groups()):
|
|
48
|
+
raise ValueError(
|
|
49
|
+
f"invalid duration {text!r}; use forms like '30m', '2h', '1h30m'."
|
|
50
|
+
)
|
|
51
|
+
h, mi, se = (int(x) if x else 0 for x in m.groups())
|
|
52
|
+
return h * 3600 + mi * 60 + se
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def max_duration(role: Role) -> int:
|
|
56
|
+
"""Cap on requested lifetime for a role.
|
|
57
|
+
|
|
58
|
+
Defaults to 1h, except uploads which may run up to 6h. A set
|
|
59
|
+
ISSUE_CREDS_MAX_LIFETIME overrides the per-role default for all roles.
|
|
60
|
+
"""
|
|
61
|
+
default = UPLOAD_MAX_DURATION if role is Role.upload else DEFAULT_MAX_DURATION
|
|
62
|
+
raw = os.environ.get("ISSUE_CREDS_MAX_LIFETIME")
|
|
63
|
+
if not raw:
|
|
64
|
+
return default
|
|
65
|
+
try:
|
|
66
|
+
return parse_duration(raw)
|
|
67
|
+
except ValueError as exc:
|
|
68
|
+
raise CredsError(f"ISSUE_CREDS_MAX_LIFETIME: {exc}") from exc
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def role_arn_for(role: Role) -> str:
|
|
72
|
+
"""Resolve the IAM role ARN for a role: its dedicated env var, else AWS_ROLE_ARN."""
|
|
73
|
+
arn = os.environ.get(_ROLE_ARN_ENV[role]) or os.environ.get("AWS_ROLE_ARN")
|
|
74
|
+
if not arn:
|
|
75
|
+
raise CredsError(
|
|
76
|
+
f"no role ARN for '{role.value}'. Set {_ROLE_ARN_ENV[role]} "
|
|
77
|
+
"or AWS_ROLE_ARN."
|
|
78
|
+
)
|
|
79
|
+
return arn
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def web_identity_token() -> str:
|
|
83
|
+
"""Read the OIDC token from AWS_WEB_IDENTITY_TOKEN_FILE (set by the hub)."""
|
|
84
|
+
path = os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE")
|
|
85
|
+
if not path:
|
|
86
|
+
raise CredsError("AWS_WEB_IDENTITY_TOKEN_FILE is not set (not on the hub?).")
|
|
87
|
+
try:
|
|
88
|
+
return Path(path).read_text().strip()
|
|
89
|
+
except OSError as exc:
|
|
90
|
+
raise CredsError(f"could not read web identity token: {exc}") from exc
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def session_name() -> str:
|
|
94
|
+
"""CloudTrail attribution lives here — prefer the real username."""
|
|
95
|
+
raw = (
|
|
96
|
+
os.environ.get("JUPYTERHUB_USER")
|
|
97
|
+
or os.environ.get("JUPYTERHUB_CLIENT_ID")
|
|
98
|
+
or "issue-creds"
|
|
99
|
+
)
|
|
100
|
+
safe = re.sub(r"[^\w+=,.@-]", "-", raw)[:64]
|
|
101
|
+
return safe if len(safe) >= 2 else f"{safe}-user"[:64]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def user_prefix() -> str:
|
|
105
|
+
"""Per-user write namespace, taken from the hub-provided username.
|
|
106
|
+
|
|
107
|
+
Used as-is (whitespace/slashes trimmed). S3 keys allow '@' and '.', so an
|
|
108
|
+
email username becomes a prefix like 'john@reflective.org/...'. Slugify here
|
|
109
|
+
if you'd rather have filesystem-safe prefixes.
|
|
110
|
+
"""
|
|
111
|
+
raw = os.environ.get("JUPYTERHUB_USER")
|
|
112
|
+
if not raw:
|
|
113
|
+
raise CredsError(
|
|
114
|
+
"JUPYTERHUB_USER is not set; cannot determine your upload prefix "
|
|
115
|
+
"(uploads are scoped to your own namespace)."
|
|
116
|
+
)
|
|
117
|
+
return raw.strip().strip("/")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def assume_role(
|
|
121
|
+
role_arn: str,
|
|
122
|
+
session: str,
|
|
123
|
+
token: str,
|
|
124
|
+
seconds: int,
|
|
125
|
+
policy: dict | None,
|
|
126
|
+
region: str | None = None,
|
|
127
|
+
) -> dict:
|
|
128
|
+
"""Call STS AssumeRoleWithWebIdentity and return the Credentials dict."""
|
|
129
|
+
params = dict(
|
|
130
|
+
RoleArn=role_arn,
|
|
131
|
+
RoleSessionName=session,
|
|
132
|
+
WebIdentityToken=token,
|
|
133
|
+
DurationSeconds=seconds,
|
|
134
|
+
)
|
|
135
|
+
if policy is not None:
|
|
136
|
+
params["Policy"] = json.dumps(policy)
|
|
137
|
+
try:
|
|
138
|
+
sts = boto3.client("sts", region_name=region)
|
|
139
|
+
resp = sts.assume_role_with_web_identity(**params)
|
|
140
|
+
except (ClientError, BotoCoreError) as exc:
|
|
141
|
+
raise CredsError(str(exc)) from exc
|
|
142
|
+
return resp["Credentials"]
|
issue_creds/errors.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Exception types for issue-creds."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CredsError(Exception):
|
|
5
|
+
"""A user-facing error. The CLI prints the message and exits non-zero.
|
|
6
|
+
|
|
7
|
+
Core/library code raises this instead of touching Typer/Click, so the
|
|
8
|
+
package stays usable (and testable) independently of the CLI layer.
|
|
9
|
+
"""
|
issue_creds/models.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Enums shared across the issue-creds package: roles and output formats."""
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Role(str, Enum):
|
|
7
|
+
"""Permission profile to request; selects which session policy is built."""
|
|
8
|
+
|
|
9
|
+
download = "download"
|
|
10
|
+
upload = "upload"
|
|
11
|
+
power = "power" # full role identity policy, no session policy applied
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OutputFormat(str, Enum):
|
|
15
|
+
"""How issued credentials are rendered to stdout."""
|
|
16
|
+
|
|
17
|
+
env = "env" # eval "$(issue-creds ...)"
|
|
18
|
+
profile = "profile" # printable ~/.aws/credentials block
|
|
19
|
+
json = "json" # human-readable
|
|
20
|
+
credential_process = "credential-process" # AWS SDK auto-refresh schema
|
issue_creds/output.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Render STS credentials into the requested output format.
|
|
2
|
+
|
|
3
|
+
Returns ``(stdout_text, stderr_note)`` rather than printing, so it can be unit
|
|
4
|
+
tested and so the CLI controls stream routing (keeping stdout clean for
|
|
5
|
+
``eval``/``credential_process`` consumers).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shlex
|
|
12
|
+
|
|
13
|
+
from .models import OutputFormat
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def render(
|
|
17
|
+
creds: dict,
|
|
18
|
+
region: str | None,
|
|
19
|
+
fmt: OutputFormat,
|
|
20
|
+
profile_name: str,
|
|
21
|
+
) -> tuple[str, str | None]:
|
|
22
|
+
"""Render an STS Credentials dict in ``fmt``, returning (stdout, stderr_note)."""
|
|
23
|
+
akid = creds["AccessKeyId"]
|
|
24
|
+
secret = creds["SecretAccessKey"]
|
|
25
|
+
token = creds["SessionToken"]
|
|
26
|
+
expiry = creds["Expiration"]
|
|
27
|
+
expiry_iso = expiry.isoformat() if hasattr(expiry, "isoformat") else str(expiry)
|
|
28
|
+
note = f"# expires {expiry_iso}"
|
|
29
|
+
|
|
30
|
+
if fmt is OutputFormat.env:
|
|
31
|
+
lines = [
|
|
32
|
+
f"export AWS_ACCESS_KEY_ID={shlex.quote(akid)}",
|
|
33
|
+
f"export AWS_SECRET_ACCESS_KEY={shlex.quote(secret)}",
|
|
34
|
+
f"export AWS_SESSION_TOKEN={shlex.quote(token)}",
|
|
35
|
+
]
|
|
36
|
+
if region:
|
|
37
|
+
lines.append(f"export AWS_DEFAULT_REGION={shlex.quote(region)}")
|
|
38
|
+
return "\n".join(lines), note
|
|
39
|
+
|
|
40
|
+
if fmt is OutputFormat.credential_process:
|
|
41
|
+
# Exact schema AWS SDKs expect from a credential_process helper.
|
|
42
|
+
return json.dumps({
|
|
43
|
+
"Version": 1,
|
|
44
|
+
"AccessKeyId": akid,
|
|
45
|
+
"SecretAccessKey": secret,
|
|
46
|
+
"SessionToken": token,
|
|
47
|
+
"Expiration": expiry_iso,
|
|
48
|
+
}), None
|
|
49
|
+
|
|
50
|
+
if fmt is OutputFormat.json:
|
|
51
|
+
return json.dumps({
|
|
52
|
+
"access_key_id": akid,
|
|
53
|
+
"secret_access_key": secret,
|
|
54
|
+
"session_token": token,
|
|
55
|
+
"expiration": expiry_iso,
|
|
56
|
+
"region": region,
|
|
57
|
+
}, indent=2), None
|
|
58
|
+
|
|
59
|
+
# profile
|
|
60
|
+
block = (
|
|
61
|
+
f"[{profile_name}]\n"
|
|
62
|
+
f"aws_access_key_id = {akid}\n"
|
|
63
|
+
f"aws_secret_access_key = {secret}\n"
|
|
64
|
+
f"aws_session_token = {token}\n"
|
|
65
|
+
)
|
|
66
|
+
if region:
|
|
67
|
+
block += f"region = {region}\n"
|
|
68
|
+
return block, note
|
issue_creds/policies.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""S3 session-policy construction.
|
|
2
|
+
|
|
3
|
+
Allow-list by default (fails closed). These policies are passed as the inline
|
|
4
|
+
`Policy` to AssumeRoleWithWebIdentity, where they can only *intersect* with the
|
|
5
|
+
role's identity policy — never widen it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from .models import Role
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _object_resource(bucket: str, prefix: str | None) -> str:
|
|
14
|
+
"""Object-level ARN: scoped to ``prefix/*`` if given, else the whole bucket."""
|
|
15
|
+
if prefix:
|
|
16
|
+
return f"arn:aws:s3:::{bucket}/{prefix.strip('/')}/*"
|
|
17
|
+
return f"arn:aws:s3:::{bucket}/*"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _list_statement(bucket: str, prefix: str | None, actions: list[str]) -> dict:
|
|
21
|
+
"""Bucket-level list statement.
|
|
22
|
+
|
|
23
|
+
ListBucket is a bucket-level action; the Resource ARN cannot scope it to a
|
|
24
|
+
prefix, so the s3:prefix condition is what actually constrains listing.
|
|
25
|
+
GetBucketLocation does NOT understand s3:prefix and must live in its own
|
|
26
|
+
unconditioned statement (see build_policy) — never fold it in here.
|
|
27
|
+
"""
|
|
28
|
+
stmt = {
|
|
29
|
+
"Sid": "ListWithinScope",
|
|
30
|
+
"Effect": "Allow",
|
|
31
|
+
"Action": actions,
|
|
32
|
+
"Resource": [f"arn:aws:s3:::{bucket}"],
|
|
33
|
+
}
|
|
34
|
+
if prefix:
|
|
35
|
+
p = prefix.strip("/")
|
|
36
|
+
stmt["Condition"] = {"StringLike": {"s3:prefix": [f"{p}/*"]}}
|
|
37
|
+
return stmt
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_policy(role: Role, bucket: str, prefix: str | None) -> dict | None:
|
|
41
|
+
"""Return an IAM session policy dict, or None for the power role."""
|
|
42
|
+
if role is Role.power:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
obj = _object_resource(bucket, prefix)
|
|
46
|
+
bucket_arn = f"arn:aws:s3:::{bucket}"
|
|
47
|
+
location = {
|
|
48
|
+
"Sid": "BucketLocation",
|
|
49
|
+
"Effect": "Allow",
|
|
50
|
+
"Action": ["s3:GetBucketLocation"],
|
|
51
|
+
"Resource": [bucket_arn],
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if role is Role.download:
|
|
55
|
+
statements = [
|
|
56
|
+
{
|
|
57
|
+
"Sid": "ReadObjects",
|
|
58
|
+
"Effect": "Allow",
|
|
59
|
+
"Action": [
|
|
60
|
+
"s3:GetObject",
|
|
61
|
+
"s3:GetObjectVersion",
|
|
62
|
+
"s3:GetObjectTagging",
|
|
63
|
+
"s3:GetObjectVersionTagging",
|
|
64
|
+
],
|
|
65
|
+
"Resource": [obj],
|
|
66
|
+
},
|
|
67
|
+
_list_statement(
|
|
68
|
+
bucket, prefix, ["s3:ListBucket", "s3:ListBucketVersions"]
|
|
69
|
+
),
|
|
70
|
+
location,
|
|
71
|
+
]
|
|
72
|
+
else: # Role.upload — write + multipart + list, deliberately no GetObject
|
|
73
|
+
statements = [
|
|
74
|
+
{
|
|
75
|
+
"Sid": "WriteObjects",
|
|
76
|
+
"Effect": "Allow",
|
|
77
|
+
"Action": [
|
|
78
|
+
"s3:PutObject",
|
|
79
|
+
"s3:PutObjectTagging",
|
|
80
|
+
"s3:AbortMultipartUpload",
|
|
81
|
+
"s3:ListMultipartUploadParts",
|
|
82
|
+
],
|
|
83
|
+
"Resource": [obj],
|
|
84
|
+
},
|
|
85
|
+
_list_statement(
|
|
86
|
+
bucket, prefix, ["s3:ListBucket", "s3:ListBucketMultipartUploads"]
|
|
87
|
+
),
|
|
88
|
+
location,
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
return {"Version": "2012-10-17", "Statement": statements}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: issue-creds
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Vend short-lived, scope-limited AWS S3 credentials on 2i2c deployed jupyterhubs.
|
|
5
|
+
Project-URL: source-code, https://github.com/ReflectiveCloud/hub-token-vending-machine
|
|
6
|
+
Project-URL: homepage, https://reflective.org
|
|
7
|
+
Author-email: John Orcutt <john@reflective.org>
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: 2i2c,aws,credentials,jupyterhub,reflective,s3,sts
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: boto3>=1.34
|
|
13
|
+
Requires-Dist: typer>=0.12
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
16
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# issue-creds
|
|
20
|
+
|
|
21
|
+
Vend short-lived, scope-limited AWS S3 credentials from inside the hub. Wraps
|
|
22
|
+
STS `AssumeRoleWithWebIdentity` and applies an inline **session policy** that can
|
|
23
|
+
only *intersect* with the role's identity policy — it can shrink permissions,
|
|
24
|
+
never widen them.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install issue-creds # from a built wheel/sdist or your index
|
|
30
|
+
# or, from a checkout:
|
|
31
|
+
pip install .
|
|
32
|
+
```
|
|
33
|
+
This installs an `issue-creds` command on `$PATH`.
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
# Read the whole bucket for 30 minutes
|
|
39
|
+
issue-creds --role download --lifetime 30m
|
|
40
|
+
# Read a single prefix
|
|
41
|
+
issue-creds --role download --prefix lagranto/runs
|
|
42
|
+
# Upload — defaults to your own JUPYTERHUB_USER prefix; --prefix overrides it
|
|
43
|
+
issue-creds --role upload
|
|
44
|
+
issue-creds --role upload --prefix shared/inbox
|
|
45
|
+
# Full role (the legacy "power user" behaviour)
|
|
46
|
+
issue-creds --role power
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Inspect what *would* be requested without calling STS:
|
|
50
|
+
```bash
|
|
51
|
+
issue-creds --role upload --bucket-scope reflective-persistent-prod --dry-run
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Other formats: `--format env` (default), `--format profile`, `--format json`.
|
|
55
|
+
|
|
56
|
+
## Roles
|
|
57
|
+
| role | grants | prefix scoping |
|
|
58
|
+
|------------|-------------------------------------------------------------------|-----------------------------------------|
|
|
59
|
+
| `download` | Get/List (+versions), GetBucketLocation | optional `--prefix` (whole bucket if omitted) |
|
|
60
|
+
| `upload` | Put, multipart, List/ListMultipart, GetBucketLocation (no Get) | defaults to `JUPYTERHUB_USER/*`; `--prefix` overrides |
|
|
61
|
+
|
|
62
|
+
## Configuration (environment)
|
|
63
|
+
| variable | purpose |
|
|
64
|
+
|---------------------------------|----------------------------------------------------------------------|
|
|
65
|
+
| `AWS_ROLE_ARN` | default role ARN (fallback for all roles) |
|
|
66
|
+
| `ISSUE_CREDS_DOWNLOAD_ROLE_ARN` | dedicated download role ARN (optional; overrides the fallback) |
|
|
67
|
+
| `ISSUE_CREDS_UPLOAD_ROLE_ARN` | dedicated upload role ARN (optional) |
|
|
68
|
+
| `ISSUE_CREDS_POWER_ROLE_ARN` | dedicated power role ARN (optional) |
|
|
69
|
+
| `ISSUE_CREDS_MAX_LIFETIME` | cap on `--lifetime` (default `1h`; `upload` allows up to `6h`); also raise the role's `MaxSessionDuration` |
|
|
70
|
+
| `AWS_WEB_IDENTITY_TOKEN_FILE` | OIDC token file (set by the hub) |
|
|
71
|
+
| `JUPYTERHUB_USER` | default upload prefix (overridable with `--prefix`) and CloudTrail session name |
|
|
72
|
+
|
|
73
|
+
## Security note
|
|
74
|
+
The session policy is **defense-in-depth, not a boundary**. Any user who can read
|
|
75
|
+
`AWS_WEB_IDENTITY_TOKEN_FILE` can call `AssumeRoleWithWebIdentity` themselves
|
|
76
|
+
without the restrictive policy and get whatever the underlying role allows. Real
|
|
77
|
+
enforcement comes from **separate, tightly-scoped IAM roles** per `download` /
|
|
78
|
+
`upload` / `power`, gated by the OIDC trust policy. Set the dedicated role ARN
|
|
79
|
+
env vars above to switch from advisory to enforced — no code change required.
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install -e .[dev]
|
|
85
|
+
pytest
|
|
86
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
issue_creds/__init__.py,sha256=JE5jzFpVybxpX0yC8zvbwvVGRk7xv1BKYl5lAiPsso0,307
|
|
2
|
+
issue_creds/cli.py,sha256=D7hFYV6sOF1y0xhlorgKQSis-uS0QdDQUukP9G9U96Q,5182
|
|
3
|
+
issue_creds/core.py,sha256=rLZQNaVq12ot5-a3hfNaL30Hz48lLhuNy-kzKto5ses,4732
|
|
4
|
+
issue_creds/errors.py,sha256=zZZVeuDEAVF7wmp4cF7XJyNDGLuGStgq2F-PPSk-sks,300
|
|
5
|
+
issue_creds/models.py,sha256=ryFWYSqwb-00Xe2x4OHbIfjLObc_68wnJEJLW8Z8uOM,725
|
|
6
|
+
issue_creds/output.py,sha256=cMeBD5A_evn2B3Tfl4DGPs8W5tfvtpqYYUnlykfXQOo,2092
|
|
7
|
+
issue_creds/policies.py,sha256=CMAbeVVCbY1GelUsTvICNse6Oe8z9OKYxCSD3RK_CQM,2983
|
|
8
|
+
issue_creds-0.1.0.dist-info/METADATA,sha256=gJjGGAlXmtxMfz-WkLPTh0HusAExJ038pCUW2tzbFDk,3871
|
|
9
|
+
issue_creds-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
10
|
+
issue_creds-0.1.0.dist-info/entry_points.txt,sha256=_52SXjp_FZZOXxnDy1Jo8ykjBXeTTycT-VnY4PK7ulg,52
|
|
11
|
+
issue_creds-0.1.0.dist-info/licenses/LICENSE,sha256=qbn0grDCVeDOEeuB4mBI_rLZ2TJ0aBlXczkecchn2KM,11341
|
|
12
|
+
issue_creds-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026, Reflective
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|