/** * A Cloud DNS client for one managed zone's record sets, over the REST * API (`https://dns.googleapis.com/dns/v1`), since Cloud DNS has no gRPC * API. * * let zone = CloudDns.connect('my-project', 'my-zone'); * await zone.put(new RecordSet('_atproto.alice.example.com.', 'TXT', 300, ['"did=did:plc:..."'])); * let set = await zone.get('_atproto.alice.example.com.', 'TXT'); * await zone.delete('_atproto.alice.example.com.', 'TXT'); * * Names are fully qualified, ending in a dot, and a TXT record's data is a * quoted string, as Cloud DNS takes them. Each call asks its `Credentials` * for an access token, with the `cloud-platform` or * `ndev.clouddns.readwrite` scope. */ import {Future} from 'zena:async'; import {Own} from 'zena:core'; import {fetch, Response} from 'zena:fetch'; import {JsonArray, JsonObject, JsonValue, parseJson, stringify} from 'zena:json'; import {EncodeSet, percentEncode} from 'zena:url'; import {Credentials} from 'protobuf/runtime'; import {defaultCredentials} from './auth.zena'; /** The origin of the Cloud DNS API. */ export let DNS_ORIGIN = 'https://dns.googleapis.com'; /** An answer from Cloud DNS that is an error, with its HTTP status. */ export class DnsError extends Error { status: i32; new(status: i32, message: String) : status = status, super(message); } /** A record set: every record of one name and type. */ export final class RecordSet { /** Fully qualified, ending in a dot. */ name: String; /** Such as `TXT` or `A`. */ type: String; /** How long resolvers may keep the records, in seconds. */ ttl: i32; /** The records' data, as the zone file writes them: a TXT record's quoted. */ rrdatas: Array; new(this.name, this.type, this.ttl, this.rrdatas); /** The record set as Cloud DNS takes it. */ toJson(): JsonObject { let json = new JsonObject(); json['name'] = this.name; json['type'] = this.type; json['ttl'] = new Box(this.ttl as f64); let rrdatas = new JsonArray(); for (let data in this.rrdatas) { rrdatas.push(data); } json['rrdatas'] = rrdatas; return json; } /** The record set in Cloud DNS's `json`. Throws `DnsError` when it is not one. */ static fromJson(json: JsonValue): RecordSet { if (!(json is JsonObject)) { throw new DnsError(0, 'the answer is not a record set'); } let object = json; let name = object['name']; let type = object['type']; let ttl = object['ttl']; let rrdatas = object['rrdatas']; if (!(name is String) || !(type is String)) { throw new DnsError(0, 'the record set has no name or type'); } let datas = new GrowableArray(); if (rrdatas is JsonArray) { let array = rrdatas; for (var i = 0; i < array.length; i += 1) { let data = array[i]; if (data is String) { datas.push(data); } } } let seconds = if (ttl is Box) ttl.value as i32 else 0; return new RecordSet(name, type, seconds, datas); } } /** One managed zone's record sets. */ export final class CloudDns { #origin: String; #credentials: Credentials; /** `/dns/v1/projects//managedZones/`. */ #zonePath: String; /** * The managed zone `zone`, a name or ID, of `project`, at `origin`, * the API's own (`DNS_ORIGIN`) unless a test serves it. */ new(project: String, zone: String, credentials: Credentials, origin: String = 'https://dns.googleapis.com') : #origin = origin, #credentials = credentials, #zonePath = `/dns/v1/projects/${percentEncode(project, EncodeSet.Component)}/managedZones/${percentEncode(zone, EncodeSet.Component)}`; /** The managed zone with the default credentials (see `defaultCredentials`). */ static connect(project: String, zone: String): CloudDns { return new CloudDns(project, zone, defaultCredentials()); } #recordPath(name: String, type: String): String { return `${this.#zonePath}/rrsets/${percentEncode(name, EncodeSet.Component)}/${percentEncode(type, EncodeSet.Component)}`; } /** The record set of `name` and `type`, or null when there is none. */ async get(name: String, type: String): Future { let response = await this.#call('GET', this.#recordPath(name, type), null); if (response.status == 404) { return null; } let text = await checked(response, `getting ${name} ${type}`); return RecordSet.fromJson(parseJson(text)); } /** * Creates `set`, or replaces the record set of its name and type when * there is one. */ async put(set: RecordSet): Future { let body = stringify(set.toJson()); let created = await this.#call('POST', `${this.#zonePath}/rrsets`, body); if (created.status != 409) { await checked(created, `creating ${set.name} ${set.type}`); return; } let patched = await this.#call('PATCH', this.#recordPath(set.name, set.type), body); await checked(patched, `replacing ${set.name} ${set.type}`); } /** Deletes the record set of `name` and `type`. Returns whether there was one. */ async delete(name: String, type: String): Future { let response = await this.#call('DELETE', this.#recordPath(name, type), null); if (response.status == 404) { return false; } await checked(response, `deleting ${name} ${type}`); return true; } async #call(method: String, path: String, body: String | null): Future> { let headers = new GrowableArray<(String, String)>(); headers.push(('accept', 'application/json')); if (body != null) { headers.push(('content-type', 'application/json')); } let authorization = await this.#credentials.authorization(); if (authorization != null) { headers.push(('authorization', authorization)); } return try { await fetch(`${this.#origin}${path}`, {method, headers, body}) } catch (e) { throw new DnsError(0, e.message) }; } } /** Returns `response`'s body text when it is a success, or throws `DnsError` naming what `doing` was. */ async function checked(response: Own, doing: String): Future { let status = response.status; let responseText = await response.text(); if (status >= 200 && status < 300) { return responseText; } var message = responseText; let json = try { parseJson(responseText) } catch (e) { null }; if (json is JsonObject) { let error = json['error']; if (error is JsonObject) { let text = error['message']; if (text is String) { message = text; } } } throw new DnsError(status, `Cloud DNS, ${doing}: HTTP ${status}: ${message}`); }