Skip to content
Merged
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
24 changes: 21 additions & 3 deletions docs/central-release-prerequisites.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ private key, a successful hosted signing operation, or current publishing rights

The manual `Read-only Sonatype namespace inventory` workflow runs only from the
repository default branch. It uses the exact workflow source, only the Sonatype
credential pair, authenticated GET requests to the fixed Portal endpoint and the
fixed `io.fireflysoftware` namespace. Credentials never enter the report. Redirects
credential pair, authenticated GET listing requests and, only for missing or null
component PURLs, an empty-body POST to the documented read-only
`/api/v1/publisher/status?id=<listed-deployment-id>` query. Both endpoints use
fixed HTTPS paths and the fixed `io.fireflysoftware` namespace. Credentials never enter the report. Redirects
and environment proxies are refused. Two bounded complete sweeps must agree;
failures produce an explicit incomplete report. Reports retain supported Maven
type/classifier identity and fixed safe reason codes. The worker limit is 120 seconds,
each response is capped at 2 MiB, and the listing is capped at 100 pages/100000 components.

The parser is copied from the independently qualified Jafly source with only its
The parser originated in the independently qualified Jafly source with its
two namespace constants adapted. Original source SHA-256:
`9a2582372c56486145fbdc74a88c76b42c913fb86d24aa430d77c1ad87889c67`.
An authenticated empty listing is distinct from a404 or incomplete listing.
Expand All @@ -47,3 +49,19 @@ Parent6 and Jafly20 remain pinned. A future Jafly23 adoption requires actual Cen
publication proof first. Parent21 and BOM7 remain unreserved by this source
change. Any later allocation must reconcile published versions and actual
account-visible staged deployments before separately reviewed release actions.

Status reconciliation validates the exact listed deployment ID and state, bounded
nonempty canonical namespace PURLs, uniqueness, and inclusion of any already known
listing coordinates. The sanitized listing and status observations must match in
two sweeps under the same outer worker deadline and total component budget.
Neither the official status response schema nor its examples assert an exhaustive
mapping from status PURLs to listing rows with missing PURLs. Those rows therefore
remain `INCOMPLETE` / `PURL_MISSING`, with `PURL_COVERAGE_UNPROVEN`; a nonempty status
PURL array never authorizes allocation or silently reclassifies an unknown row.
Names, paths, errors, raw bodies, and credentials never supply missing coordinates.

This boundary follows the official [Publisher API](https://central.sonatype.com/api-doc)
and [status query documentation](https://central.sonatype.org/publish/publish-portal-api/#checking-status).
A separately established complete coordinate contract is still required to resolve
unknown-row coverage. This source change does not establish authenticated account
visibility, historical reservation completeness, or a successful Portal query.
68 changes: 64 additions & 4 deletions scripts/sonatype_deployments.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import urllib.request

ENDPOINT = 'https://central.sonatype.com/api/v1/publisher/deployments'
STATUS_ENDPOINT = 'https://central.sonatype.com/api/v1/publisher/status'
NAMESPACE = 'io.fireflysoftware'
STATES = {'VALIDATING', 'VALIDATED', 'PUBLISHING', 'PUBLISHED', 'FAILED'}
MAX_BYTES = 2 * 1024 * 1024
Expand Down Expand Up @@ -67,6 +68,20 @@ def fetch(opener, bearer, page, size):
url = ENDPOINT + '?' + query
request = urllib.request.Request(url, headers={'Authorization': 'Bearer ' + bearer,
'Accept': 'application/json', 'Accept-Encoding': 'identity'}, method='GET')
return fetch_json(opener, request)


def fetch_status(opener, bearer, identifier):
if not isinstance(identifier, str) or not IDENTIFIER.fullmatch(identifier):
raise InventoryError('Portal status deployment identity is unsupported.')
url = STATUS_ENDPOINT + '?' + urllib.parse.urlencode({'id': identifier})
request = urllib.request.Request(url, data=b'', headers={'Authorization': 'Bearer ' + bearer,
'Accept': 'application/json', 'Accept-Encoding': 'identity'}, method='POST')
return fetch_json(opener, request)


def fetch_json(opener, request):
url = request.full_url
try:
with opener.open(request, timeout=10) as response:
if response.status != 200 or response.geturl() != url:
Expand Down Expand Up @@ -192,7 +207,7 @@ def maven_coordinate(component):
return artifact, version, tuple(sorted(qualifiers.items()))


def project(row):
def project(row, missing=None):
if not isinstance(row, dict):
raise InventoryError('Portal deployment is unsupported.')
identifier = row.get('deploymentId')
Expand All @@ -205,7 +220,13 @@ def project(row):
raise InventoryError('Portal deployment components are missing or unsupported.')
coordinates = set()
for component in components:
coordinates.add(maven_coordinate(component))
try:
coordinates.add(maven_coordinate(component))
except InventoryError as error:
if (missing is None or error.reason_code != 'PURL_MISSING'
or not isinstance(component, dict) or component.get('purl') is not None):
raise
missing.append(error.component_schema)
return {'deploymentId': identifier, 'state': state,
'createTimestamp': timestamp(row.get('createTimestamp')),
'updateTimestamp': timestamp(row.get('updateTimestamp')),
Expand All @@ -214,6 +235,32 @@ def project(row):
for artifact, version, qualifiers in sorted(coordinates)]}


def reconcile_status(opener, bearer, safe, missing):
reply = fetch_status(opener, bearer, safe['deploymentId'])
if reply.get('deploymentId') != safe['deploymentId'] or reply.get('deploymentState') != safe['state']:
raise InventoryError('Portal status identity or state does not match its listed deployment.')
purls = reply.get('purls')
if not isinstance(purls, list) or not purls or len(purls) > 10000:
raise InventoryError('Portal status PURLs are missing or unsupported.')
coordinates = set()
for purl in purls:
coordinate = maven_coordinate({'purl': purl})
if coordinate in coordinates:
raise InventoryError('Portal status PURLs have ambiguous duplicate identities.')
coordinates.add(coordinate)
known = {(item['artifactId'], item['version'], tuple(sorted(item.get('qualifiers', {}).items())))
for item in safe['components']}
if not known.issubset(coordinates):
raise InventoryError('Portal status omits known listing coordinates.')
safe['statusComponents'] = [{'groupId': NAMESPACE, 'artifactId': artifact, 'version': version,
**({'qualifiers': dict(qualifiers)} if qualifiers else {})}
for artifact, version, qualifiers in sorted(coordinates)]
# The published status contract does not map these PURLs to missing listing rows.
safe['unresolvedComponentCount'] = len(missing)
safe['componentSchema'] = missing[0]
return len(purls)


def sweep(opener, bearer, page_size):
rows = []
identifiers = set()
Expand All @@ -239,11 +286,14 @@ def sweep(opener, bearer, page_size):
if not isinstance(deployments, list) or len(deployments) != min(size, total - number * size):
raise InventoryError('Portal page is incomplete.')
for row in deployments:
safe = project(row)
missing = []
safe = project(row, missing)
if safe['deploymentId'] in identifiers:
raise InventoryError('Portal deployment was repeated across pages.')
identifiers.add(safe['deploymentId'])
total_components += len(row['deploymentComponents'])
if missing:
total_components += reconcile_status(opener, bearer, safe, missing)
if total_components > MAX_COMPONENTS:
raise InventoryError('Portal inventory exceeded the component limit.')
rows.append(safe)
Expand All @@ -266,6 +316,16 @@ def collect(bearer, opener=None, page_size=100):
if first != second:
raise InventoryError('Portal inventory changed between complete sweeps.')
metadata, rows = first
unresolved = [row for row in rows if 'unresolvedComponentCount' in row]
if unresolved:
report = incomplete('Portal component Maven coordinates are unsupported.', 'PURL_MISSING',
unresolved[0]['componentSchema'])
report['statusReconciliation'] = {
'coverage': 'PURL_COVERAGE_UNPROVEN', 'matchingSweeps': 2,
'unresolvedComponentCount': sum(row['unresolvedComponentCount'] for row in unresolved),
'deployments': [{key: value for key, value in row.items() if key != 'componentSchema'}
for row in rows]}
return report
return {'schema': 1, 'status': 'ACCOUNT_VISIBLE_NAMESPACE_STABLE_TWO_SWEEPS',
'namespace': NAMESPACE, 'endpoint': ENDPOINT, 'atomicSnapshot': False,
'completenessScope': 'Documented account-visible namespace listing; two identical complete sweeps only.',
Expand Down Expand Up @@ -294,7 +354,7 @@ def worker(output):
bearer = token(os.environ.get('SONATYPE_USERNAME', ''), os.environ.get('SONATYPE_PASSWORD', ''))
report = collect(bearer)
write_report(output, report)
return 0
return 0 if report['status'] == 'ACCOUNT_VISIBLE_NAMESPACE_STABLE_TWO_SWEEPS' else 1
except InventoryError as error:
write_report(output, incomplete(str(error), error.reason_code, error.component_schema))
return 1
Expand Down
4 changes: 3 additions & 1 deletion tests/test_sonatype_deployments.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,9 @@ def test_worker_report_contains_only_fixed_failure_code_not_the_purl(self):
class ComponentDiagnosticTests(unittest.TestCase):
def report(self, component):
row = deployment(); row['deploymentComponents'] = [component]
api = Api([page([row])])
status = {'deploymentId': row['deploymentId'], 'deploymentState': row['deploymentState'],
'purls': ['pkg:maven/io.fireflysoftware/diagnostic@1']}
api = Api([page([row]), status, page([copy.deepcopy(row)]), copy.deepcopy(status)])
with tempfile.TemporaryDirectory() as directory:
out = Path(directory) / 'report.json'
with patch.dict(os.environ, {'SONATYPE_USERNAME': 'synthetic', 'SONATYPE_PASSWORD': 'synthetic'}, clear=True), \
Expand Down
157 changes: 157 additions & 0 deletions tests/test_sonatype_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""Status is read-only evidence, never an invented missing-row coordinate mapping."""
import copy
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import urllib.error
import io
from test_sonatype_deployments import m, Api, Response, deployment, page

STATUS_URL = 'https://central.sonatype.com/api/v1/publisher/status?id=deployment-1'
PURL = 'pkg:maven/io.fireflysoftware/firefly-parent@26.10.6?type=pom'


def unknown():
row = deployment()
row['deploymentComponents'][0]['purl'] = None
return row


def status(purls=None):
return {'deploymentId': 'deployment-1', 'deploymentState': 'VALIDATED',
'deploymentName': 'PRIVATE-NAME', 'purls': [PURL] if purls is None else purls,
'errors': {'PRIVATE-KEY': ['PRIVATE-ERROR']}}


class StatusReconciliationTests(unittest.TestCase):
def collect(self, rows=None, observation=None):
rows = [unknown()] if rows is None else rows
observation = status() if observation is None else observation
api = Api([page(rows), observation, page(copy.deepcopy(rows)), copy.deepcopy(observation)])
return m.collect('TOKEN-SENTINEL', opener=api, page_size=2), api

def test_valid_status_does_not_invent_unknown_component_coverage(self):
result, api = self.collect()
self.assertEqual('INCOMPLETE', result['status'])
self.assertEqual('PURL_MISSING', result['reasonCode'])
self.assertEqual('PURL_COVERAGE_UNPROVEN', result['statusReconciliation']['coverage'])
self.assertEqual(1, result['statusReconciliation']['unresolvedComponentCount'])
self.assertEqual([{'groupId':'io.fireflysoftware', 'artifactId':'firefly-parent',
'version':'26.10.6', 'qualifiers':{'type':'pom'}}],
result['statusReconciliation']['deployments'][0]['statusComponents'])
self.assertFalse(result['versionAllocated'])
self.assertNotIn('PRIVATE-', json.dumps(result))
self.assertNotIn('TOKEN-SENTINEL', json.dumps(result))
self.assertEqual(4, len(api.requests))

def test_only_exact_listed_id_empty_body_fixed_post_is_issued(self):
_, api = self.collect()
self.assertEqual(['GET', 'POST', 'GET', 'POST'], [r.get_method() for r, _ in api.requests])
for request, timeout in api.requests[1::2]:
self.assertEqual(STATUS_URL, request.full_url)
self.assertEqual(b'', request.data)
self.assertEqual('Bearer TOKEN-SENTINEL', request.get_header('Authorization'))
self.assertEqual('identity', request.get_header('Accept-encoding'))
self.assertLessEqual(timeout, 10)

def test_status_identity_state_and_shape_are_validated(self):
changes = [{'deploymentId':'different'}, {'deploymentState':'PUBLISHED'},
{'deploymentId':None}, {'deploymentState':'PENDING'},
{'purls':None}, {'purls':[]}, {'purls':'PRIVATE'}, {'purls':[None]}]
for change in changes:
value = status(); value.update(change)
with self.subTest(change=change), self.assertRaises(m.InventoryError):
self.collect(observation=value)

def test_status_namespace_encoding_qualifiers_and_duplicates_are_not_relaxed(self):
for purls in [['pkg:maven/evil/a@1'], [PURL, PURL],
['pkg:maven/io.fireflysoftware/a@1', 'pkg:maven/io.fireflysoftware/a@1?type=jar'],
['pkg:maven/io.fireflysoftware/a@1?unknown=PRIVATE'],
['pkg:maven/io.fireflysoftware/a@1%252FPRIVATE']]:
with self.subTest(purls=purls), self.assertRaises(m.InventoryError):
self.collect(observation=status(purls))

def test_mixed_known_listing_coordinate_must_be_present_in_status(self):
row = unknown(); row['deploymentComponents'].append({'purl':'pkg:maven/io.fireflysoftware/a@1'})
with self.assertRaises(m.InventoryError): self.collect([row])
result, _ = self.collect([row], status([PURL, 'pkg:maven/io.fireflysoftware/a@1']))
self.assertEqual('INCOMPLETE', result['status'])
self.assertEqual(1, result['statusReconciliation']['unresolvedComponentCount'])

def test_status_and_unresolved_count_must_match_across_sweeps(self):
for second_status, second_row in [(status([PURL.replace('26.10.6','26.10.7')]), unknown()),
(status(), deployment())]:
api = Api([page([unknown()]), status(), page([second_row]), second_status])
with self.subTest(second_status=second_status), self.assertRaises(m.InventoryError):
m.collect('TOKEN', opener=api, page_size=2)

def test_invalid_listing_is_rejected_before_status_lookup(self):
for change in [{'namespace':'evil'}, {'deploymentId':'../evil'},
{'createTimestamp':None}, {'deploymentState':'PENDING'}]:
row = unknown(); row.update(change); api = Api([page([row])])
with self.subTest(change=change), self.assertRaises(m.InventoryError):
m.collect('TOKEN', opener=api, page_size=2)
self.assertEqual(['GET'], [r.get_method() for r, _ in api.requests])
row = unknown(); row['deploymentComponents'].append({'purl':'pkg:maven/evil/a@1'})
api = Api([page([row])])
with self.assertRaises(m.InventoryError): m.collect('TOKEN', opener=api, page_size=2)
self.assertEqual(1,len(api.requests))

def test_known_inventory_never_makes_status_requests(self):
api = Api([page(), page()])
result = m.collect('TOKEN', opener=api, page_size=2)
self.assertEqual('ACCOUNT_VISIBLE_NAMESPACE_STABLE_TWO_SWEEPS',result['status'])
self.assertEqual(['GET','GET'],[r.get_method() for r,_ in api.requests])

def test_status_transport_shares_url_content_json_and_byte_guards(self):
replies = [Response(status(),'https://evil.example'),
Response(b'{"purls":[],"purls":[]}',STATUS_URL),
Response(b' '*(2*1024*1024+1),STATUS_URL),
Response(b'[]',STATUS_URL), Response(b'\xff',STATUS_URL)]
for reply in replies:
api = Api([page([unknown()]),reply])
with self.subTest(reply=type(reply).__name__), self.assertRaises(m.InventoryError):
m.collect('TOKEN',opener=api,page_size=2)
reply = Response(status(),STATUS_URL); reply.headers={'Content-Type':'text/html'}
with self.assertRaises(m.InventoryError):
m.collect('TOKEN',opener=Api([page([unknown()]),reply]),page_size=2)

def test_status_http_and_transport_errors_never_leak_private_values(self):
for error in [OSError('PRIVATE-ERROR TOKEN-SENTINEL'),
urllib.error.HTTPError(STATUS_URL,403,'PRIVATE-ERROR',{},io.BytesIO(b'PRIVATE-BODY'))]:
with self.assertRaises(m.InventoryError) as caught:
m.collect('TOKEN',opener=Api([page([unknown()]),error]),page_size=2)
self.assertNotIn('PRIVATE-',str(caught.exception))
self.assertNotIn('TOKEN',str(caught.exception))

def test_status_cardinality_is_bounded_and_input_not_mutated(self):
value=status([PURL]*10001)
with self.assertRaises(m.InventoryError): self.collect(observation=value)
row=unknown(); before=copy.deepcopy(row)
self.collect([row]); self.assertEqual(before,row)

def test_status_observations_share_total_component_budget(self):
with patch.object(m,'MAX_COMPONENTS',1), self.assertRaises(m.InventoryError):
self.collect()

def test_worker_returns_failure_for_stable_unproven_status_evidence(self):
api=Api([page([unknown()]),status(),page([unknown()]),status()])
with tempfile.TemporaryDirectory() as directory:
output=Path(directory)/'report.json'
with patch.dict(m.os.environ,{'SONATYPE_USERNAME':'synthetic','SONATYPE_PASSWORD':'synthetic'},clear=True), \
patch.object(m.urllib.request,'build_opener',return_value=api):
self.assertEqual(1,m.worker(output))
result=json.loads(output.read_text())
self.assertEqual('PURL_COVERAGE_UNPROVEN',result['statusReconciliation']['coverage'])
self.assertEqual(0o600,output.stat().st_mode&0o777)

def test_missing_listing_queries_status_before_closed_completeness_decision(self):
api=Api([page([unknown()]),status(),page([unknown()]),status()])
try:
result=m.collect('TOKEN',opener=api,page_size=2)
except m.InventoryError:
result=None
self.assertEqual(2,sum(request.get_method()=='POST' for request,_ in api.requests))
self.assertEqual('INCOMPLETE',result['status'])
Loading