mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 23:59:27 -05:00
Under enforcement a REST route no rule maps and no vendored model names
runs unchecked. AWS AppConfig with its data plane, AWS CodeArtifact and
Amazon CodeGuru Reviewer were among those: Floci serves each and no rule
mapped them.
Vendors the appconfig, appconfigdata, codeartifact and codeguru-reviewer
models' routes, 120 operations, so each request is checked as its
operation's action: a caller holding no grant for one is now refused
where the request used to pass. A request signed with a vendored model's
own name, which Floci also serves (appconfigdata), is checked under the
signing name the routes file records for that model (appconfig).
The three namespaces join the table of request resources. CodeArtifact's
48 operations and CodeGuru Reviewer's 14 read every type the Service
Authorization Reference marks required. Nine of AppConfig's 58 act on a
required type the table reads no member for (a deployment, a hosted
configuration version, an experiment run, a configuration profile named
as Configuration), so those are checked on the types it does read.
AppConfig Data's StartConfigurationSession is checked on the application
its ApplicationIdentifier names by its id or its name, from a measured
entry quoting AWS's own refusal of it on application/<app_id>, and
GetLatestConfiguration on the configuration of the session its
ConfigurationToken names: a reading gives a request's token that a
create of its service answers as naming what that create's session is
on, which the service finds.
A request member whose botocore shape is an account id now gives the
account of what the request names wherever a REST request carries it,
its path and query too, as the generator's own rule says, not only in
its body: CodeArtifact's domain-owner, QuickSight's AwsAccountId path
label on 196 operations, and Signer's GetSigningProfile profileOwner.
Such a resource in another account than the caller's is named as an ARN
of another account already is, in that account and as the caller's of
that name too, unless its service acts on it in that account. Signer,
ECR, CodeArtifact and Redshift do and say so, so each is checked on that
account's resource alone, as AWS checks it: Signer now reads the profile
or job its profileOwner or jobOwner names in that account, as AWS does,
where it read the caller's own, and saves a job it revokes there. Such a
request needs the owner's grant beside the caller's own policy, as AWS
requires of a cross-account request: CodeArtifact gives IAM a domain's
and a repository's policy, and Signer the profile permissions
AddProfilePermission adds, as the resource's policy (ResourcePolicyProvider),
a permission of one profile version holding for that version alone: a
job's, the version that signed it.
A resource a request names by another spelling than its service stores
it under is checked as the service reads it (resolveStoredArn, now also
for an ARN the reader builds from members): an AppConfig environment or
configuration profile by its id when named by its name, a CodeArtifact
PyPI or NuGet package by its normalized name, as AWS writes it in ARNs.
AppConfig, CodeArtifact and CodeGuru Reviewer give IAM the tags they hold
on the resource a request names (an application, a domain, repository or
package group, an association), so a grant conditioned on aws:ResourceTag
reaches a tagged resource; Signer reads a profile's tags in the profile's
own account, another account's included. A tagged create is checked for tagging on what
it makes where botocore's response gives it: CreateEnvironment answers
an Environment whose Id is the new environment's, AssociateRepository
the RepositoryAssociation whose AssociationArn is the association it
makes. A tagged StartDeployment's tags go on the deployment it makes,
its DeploymentNumber AppConfig's to mint, open. AppConfig stays out of
the passed-roles table: CreateExtension and UpdateExtension pass a role
in Actions{}[].RoleArn, a map of lists that file does not read.
A new vendored source, tools/aws/sources/codeartifact-permissions.json,
written by its own script from the CodeArtifact user guide, gives what
neither botocore nor the Service Reference says: CopyPackageVersions is
checked as ReadFromRepository on its source repository and as
CopyPackageVersions on its destination repository, and a package with
no namespace has an empty one in its ARN (package/my_domain/my_repo/
npm//react), so a request leaving namespace out is checked on that ARN.
A variable the reference names Encoded and a botocore shape's name is
filled from the member of that shape and encoded as its service encodes
it, through StoredResourceArns: CodeArtifact's package group pattern,
percent-encoded in lower case, which CodeArtifact now writes into the
group's own ARN as AWS does (/npm/team/* is /npm/team/%2a). A tag call
spelling a group's pattern otherwise (%2A), which CodeArtifact reads as
the same group, is checked on the group's own ARN, which CodeArtifact
resolves it to, so a deny on that ARN holds.
With AppConfig in the table, a tag call naming one of its ARNs with the
slash unencoded is refused as a path its model does not give, as for
every namespace the table reads; AppConfig's tests now send the ARN
encoded, as an SDK does. AppConfig Data's GetLatestConfiguration, which
a route filter moves off GET /configuration so S3's bucket of that name
keeps its route, is moved under an internal prefix the request records,
as every such route is, so IAM matches it on its modeled path. The table
tests place a create's members where the table locates them, expect a
member holding the type's own ARN to name it as it is, and expect each
resource in the account its own account member gives.
168 lines
8.4 KiB
Python
168 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the AWS CodeArtifact user guide says a request is checked on, where neither botocore nor the Service
|
|
Reference says it, into tools/aws/sources/codeartifact-permissions.json, a source of the IAM tables.
|
|
|
|
The guide's page on copying packages gives the permissions CopyPackageVersions is checked as, each on the repository
|
|
of the request it names:
|
|
|
|
The user calling copy-package-versions must have the ReadFromRepository permission on the source repository and
|
|
the CopyPackageVersions permission on the destination repository.
|
|
|
|
https://docs.aws.amazon.com/codeartifact/latest/ug/copy-package.html
|
|
|
|
The Service Reference lists `package` and `repository` for CopyPackageVersions and `repository` for
|
|
ReadFromRepository, but not which repository of the request each is checked on, and botocore does not say it as data
|
|
either. Its page on repository policies gives the ARN of a package that has no namespace, which the Service
|
|
Reference's `package` format, `package/${DomainName}/${RepositoryName}/${PackageFormat}/${PackageNamespace}/
|
|
${PackageName}`, leaves to the request:
|
|
|
|
The ARN for an npm package without a scope has the empty string for the namespace field. For example, the
|
|
following is the ARN for a package without a scope and with name react in the my_repo repository in domain
|
|
my_domain.
|
|
arn:aws:codeartifact:region-id:111122223333:package/my_domain/my_repo/npm//react
|
|
|
|
https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html
|
|
|
|
This script copies each sentence of the first kind as it stands, with the operation its command calls and each
|
|
permission it names and the resource it names it on, and each example ARN of the second page with the paragraph it
|
|
follows. Nothing in the output is written by hand, and the generator reads it against botocore's requests.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_codeartifact_permissions.py # rewrite the vendored file from the pages
|
|
python3 tools/aws/fetch_codeartifact_permissions.py --verify # online: the file still says what the pages do
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
COPY_PAGE = "https://docs.aws.amazon.com/codeartifact/latest/ug/copy-package.html"
|
|
POLICIES_PAGE = "https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/codeartifact-permissions.json"
|
|
|
|
# A sentence giving the permissions the command it names is checked as, each on a resource of its request.
|
|
CALLER_RE = re.compile(r"^The user calling (?P<command>[a-z]+(?:-[a-z]+)+) must have (?P<clauses>.+)\.$")
|
|
# One permission of such a sentence and the resource it is checked on.
|
|
CLAUSE_RE = re.compile(r"^the (?P<action>[A-Z][A-Za-z]+) permission on the (?P<resource>[a-z]+(?: [a-z]+)*)$")
|
|
# A paragraph saying the code block after it is the ARN of something.
|
|
ARN_LEAD_RE = re.compile(r"\bthe following is the ARN for\b")
|
|
# A paragraph and the code block right after it.
|
|
EXAMPLE_RE = re.compile(r"<p>(?P<lead>(?:(?!</p>).)*?)</p>\s*<pre[^>]*>(?P<code>.*?)</pre>", re.S)
|
|
|
|
|
|
def text(fragment: str) -> str:
|
|
"""A fragment of the page as text, spaces collapsed."""
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
|
|
|
|
|
|
def code(fragment: str) -> str:
|
|
"""A code block as the text it shows, the page's copy button left out and nothing put between its parts."""
|
|
fragment = re.sub(r'<div class="code-btn-container">.*?</div></div>', "", fragment, flags=re.S)
|
|
return html.unescape(re.sub(r"<[^>]+>", "", re.sub(r"<!--.*?-->", "", fragment, flags=re.S))).strip()
|
|
|
|
|
|
def operation_of(command: str) -> str:
|
|
"""The API operation a CLI command calls: `copy-package-versions` calls CopyPackageVersions."""
|
|
return "".join(word.capitalize() for word in command.split("-"))
|
|
|
|
|
|
def read_caller_permissions(page: str) -> list[dict]:
|
|
"""Each sentence of the page giving the permissions a command is checked as, with the operation it calls and each
|
|
permission it names, as an action of the namespace, and the resource of the request it names it on."""
|
|
found = []
|
|
for paragraph in re.findall(r"<p>(.*?)</p>", page, re.S):
|
|
sentence = text(paragraph)
|
|
match = CALLER_RE.match(sentence)
|
|
if match is None:
|
|
continue
|
|
clauses = [CLAUSE_RE.match(clause) for clause in match.group("clauses").split(" and ")]
|
|
if not all(clauses):
|
|
raise ValueError(f"{COPY_PAGE} says '{sentence}', which does not name each permission and its "
|
|
f"resource as it did: its layout changed")
|
|
found.append({"operation": operation_of(match.group("command")), "sentence": sentence,
|
|
"permissions": [{"action": "codeartifact:" + clause.group("action"),
|
|
"resource": clause.group("resource")} for clause in clauses]})
|
|
if not found:
|
|
raise ValueError(f"{COPY_PAGE} says no permissions a command is checked as: its layout changed")
|
|
return found
|
|
|
|
|
|
def read_arn_examples(page: str) -> list[dict]:
|
|
"""Each ARN the page gives in a code block after a paragraph saying what it is the ARN for, with that paragraph."""
|
|
found = [{"paragraph": text(match.group("lead")), "arn": code(match.group("code"))}
|
|
for match in EXAMPLE_RE.finditer(page) if ARN_LEAD_RE.search(text(match.group("lead")))]
|
|
found = [example for example in found if example["arn"].startswith("arn:")]
|
|
if not found:
|
|
raise ValueError(f"{POLICIES_PAGE} gives no example ARN after a paragraph saying what it is for: its "
|
|
f"layout changed")
|
|
return found
|
|
|
|
|
|
def build(copy_page: str, policies_page: str) -> dict:
|
|
return {
|
|
"_source": {
|
|
"pages": [COPY_PAGE, POLICIES_PAGE],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "Each sentence of the copy page giving the permissions a command is checked as, copied as it "
|
|
"stands, with the operation its command calls and each permission it names and the resource it "
|
|
"names it on; and each example ARN of the repository policies page with the paragraph it "
|
|
"follows.",
|
|
},
|
|
"callerPermissions": read_caller_permissions(copy_page),
|
|
"arnExamples": read_arn_examples(policies_page),
|
|
}
|
|
|
|
|
|
def fetch_url(url: str) -> str:
|
|
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
|
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
return response.read().decode("utf-8")
|
|
|
|
|
|
def fetch_all(fetch=fetch_url) -> tuple[str, str]:
|
|
"""The copy page and the repository policies page."""
|
|
return fetch(COPY_PAGE), fetch(POLICIES_PAGE)
|
|
|
|
|
|
def stale(vendored: dict, copy_page: str, policies_page: str) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(copy_page, policies_page)
|
|
return any(vendored.get(key) != built[key] for key in built if key != "_source")
|
|
|
|
|
|
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
pages = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the AWS CodeArtifact documentation ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, *pages):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what {COPY_PAGE} and {POLICIES_PAGE} do: "
|
|
f"run tools/aws/fetch_codeartifact_permissions.py and then make iam-request-resources-sync",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches {COPY_PAGE} and {POLICIES_PAGE}")
|
|
return 0
|
|
built = build(*pages)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['callerPermissions'])} operations' permissions, "
|
|
f"{len(built['arnExamples'])} example ARNs)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|