Experiments and implementations · Intermediate

Test an API authorization boundary from a permission table

Exercise a local document API as owner, read-only user, stranger and anonymous caller, checking rejected responses and unchanged state.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Write the permission table before implementation
  2. Keep the authentication fixture separate from authorization
  3. Authorize before changing state
  4. Run requests through a separate local server
  5. Pair successful and rejected behavior
  6. Change identity claims and current grants
  7. Exercise: change one policy requirement
  8. Ask Logeia about this articleCheck your understanding

Write the permission table before implementation

Document D belongs to A and is shared read-only with B. C is authenticated but has no grant; an anonymous request has no actor. The table allows A’s GET and PUT and B’s GET, while rejecting B’s PUT and C’s GET. Establish these expected outcomes before looking at implementation behavior. Authentication alone would miss the distinction between B and C’s permitted operations. A rejected PUT response is also insufficient if the document was already changed before that response. Compare status, returned content and retained state as separate observations. This experiment covers one document’s retrieval and update boundary, not additional routes such as search or attachments that the teaching service does not implement.

Keep the authentication fixture separate from authorization

The program starts a local HTTP server on 127.0.0.1 using an automatically selected port. Fixed strings such as token-A map to actors through a dictionary solely to select test cases. This is an authentication fixture, not a secure production login implementation. The tested responsibility begins after that fixture resolves an actor. Adding user_id=A to a request does not change verified test actor B, which checks that caller-supplied identity claims do not override the actor source. A production service separately needs secure session issuance, unpredictability, expiration, revocation and transport protection. Those are explicitly outside this fixture, and the known token strings must not be copied as a recommended authentication mechanism.

Authorize before changing state

The process method resolves an actor, validates the requested target and decides permission before modifying the body. A write request from anyone other than the owner stops before the update. The read-only branch includes not write so B’s reading grant cannot silently authorize a PUT. Rejected responses contain an error field without the document body. These are ordering and information-release contracts, not simply presentation choices. The updated body is deliberately a fixed teaching value, keeping payload parsing and size validation outside this particular experiment. A real API needs those checks too, but successful parsing cannot replace permission. Follow exactly which conditions are satisfied before the write executes rather than assuming that a final error response proves the state stayed intact.

Run requests through a separate local server

Save the complete code as permission_test.py and run it with Python 3.12 or a compatible later version. It uses only the standard library and never contacts an external service or production database. Requests cross an actual local HTTP boundary, exercising header and method handling rather than only calling a decision function directly. The local client explicitly bypasses proxy use for this loopback test. The document is fictional in-memory data discarded when the process ends. Passing assertions print a summary covering owner, reader, stranger, anonymous, identity-claim and revocation cases. A finally block shuts down the server and waits for its thread, so rerunning the file does not depend on an earlier server instance. The meaningful evidence is each response and state transition, not the randomly chosen port.

python
import json, threading, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sessions = {'token-A':'A', 'token-B':'B', 'token-C':'C'}
doc = {'id':'D', 'owner':'A', 'readers':{'B'}, 'body':'draft'}
class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args): pass
    def respond(self, status, payload):
        data = json.dumps(payload).encode()
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)
    def process(self, write):
        actor = sessions.get(self.headers.get('Authorization','').removeprefix('Bearer '))
        if actor is None:
            return self.respond(401, {'error':'unauthenticated'})
        if self.path.split('?')[0] != '/documents/D':
            return self.respond(404, {'error':'not found'})
        allowed = actor == doc['owner'] or (not write and actor in doc['readers'])
        if not allowed:
            return self.respond(403, {'error':'forbidden'})
        if write:
            doc['body'] = 'updated'
        return self.respond(200, {'body':doc['body']})
    def do_GET(self): self.process(False)
    def do_PUT(self): self.process(True)
server = ThreadingHTTPServer(('127.0.0.1',0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def request(actor, method='GET', suffix=''):
    headers = {'Authorization':'Bearer token-'+actor} if actor else {}
    req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/documents/D'+suffix, headers=headers, method=method)
    try:
        response = opener.open(req, timeout=3)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status, json.loads(response.read())
try:
    assert request('A')[0] == 200
    assert request('B')[0] == 200
    for actor, method, expected in [('B','PUT',403), ('C','GET',403), (None,'GET',401)]:
        status, body = request(actor, method)
        assert status == expected and 'body' not in body and doc['body'] == 'draft'
    assert request('B','PUT','?user_id=A')[0] == 403
    assert request('A','PUT') == (200, {'body':'updated'})
    doc['readers'].clear()
    assert request('B')[0] == 403
    print('owner/read-only/stranger/anonymous/spoof/revocation: passed')
finally:
    server.shutdown(); thread.join(); server.server_close()

Pair successful and rejected behavior

The first cases establish that A and B can read, then the test exercises forbidden operations. B’s PUT, C’s GET and an anonymous GET each have an expected status, no returned body field and unchanged draft content. The later authorized PUT by A must change the body to updated, so an implementation rejecting every write cannot pass. This paired structure verifies functionality and protection together. It is also more than memorizing status-code names: the distinction follows separate conditions for actor resolution and operation permission. A product may choose a different disclosure policy for response details, but its tests must still inspect retained state and protected content alongside the visible error response.

Change identity claims and current grants

B’s PUT remains forbidden even when its query includes user_id=A because actor identity is not taken from that field. Well-formed input is not the same as verified ownership. The revocation test clears the reader set and then rejects B’s next GET; a previous successful read does not authorize every future request. This does not demonstrate deletion of content already delivered to B. Nor does the small implementation solve every race between policy inspection and a concurrent update. Moving the example to persistent storage requires separate decisions about atomic authorization and writes, cache invalidation and failures. State the tested scope so that one passing request sequence is not mistaken for evidence about guarantees the service never implemented.

Exercise: change one policy requirement

Suppose B should also receive update permission. Identify the policy change and the tests that must change before editing code. A worked design replaces the owner-only write rule with an operation-specific sharing rule. B’s PUT becomes permitted, while C’s PUT and an anonymous PUT remain rejected; revoking B’s grant must reject B’s later PUT as well. Merely deleting not write would turn every current reader into an editor, which may exceed the intended change. Write the revised table first, then choose conditions and regression tests. This exercise describes a proposed extension, not behavior already implemented by the published program. Keep actual execution evidence separate from predictions about a later design.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 19

Choose a learning path