├── CODEOWNERS ├── Makefile ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── locales ├── pcp-common.pot └── eo.po ├── README.md ├── test └── puppetlabs │ └── pcp │ ├── protocol_test.clj │ ├── message_v2_test.clj │ └── message_v1_test.clj ├── src └── puppetlabs │ └── pcp │ ├── message_v2.clj │ ├── protocol.clj │ └── message_v1.clj ├── .github └── workflows │ └── mend.yaml ├── project.clj ├── CHANGELOG.md ├── dev-resources └── Makefile.i18n └── LICENSE /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # default to skeletor 2 | * @puppetlabs/skeletor 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PACKAGES=puppetlabs.pcp.message 2 | include dev-resources/Makefile.i18n 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /resources/locales.clj 9 | /.lein-* 10 | /.nrepl-port 11 | *~ 12 | /.idea 13 | *.iml 14 | /dev-resources/i18n/bin 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | sudo: false 3 | lein: 2.8.1 4 | jdk: 5 | - openjdk8 6 | - openjdk11 7 | script: 8 | - lein test 9 | - lein with-profile test-schema-validation test 10 | notifications: 11 | email: false 12 | 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | Third-party patches are essential for keeping puppet open-source projects 4 | great. We want to keep it as easy as possible to contribute changes that 5 | allow you to get the most out of our projects. There are a few guidelines 6 | that we need contributors to follow so that we can have a chance of keeping on 7 | top of things. For more info, see our canonical guide to contributing: 8 | 9 | [https://github.com/puppetlabs/puppet/blob/master/CONTRIBUTING.md](https://github.com/puppetlabs/puppet/blob/master/CONTRIBUTING.md) 10 | -------------------------------------------------------------------------------- /locales/pcp-common.pot: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR Puppet 3 | # This file is distributed under the same license as the puppetlabs.pcp_common package. 4 | # FIRST AUTHOR , YEAR. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: puppetlabs.pcp_common \n" 10 | "Report-Msgid-Bugs-To: docs@puppet.com\n" 11 | "POT-Creation-Date: \n" 12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 | "Last-Translator: FULL NAME \n" 14 | "Language-Team: LANGUAGE \n" 15 | "Language: \n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=UTF-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | 20 | #: src/puppetlabs/pcp/message_v1.clj 21 | msgid "first chunk should be type 1" 22 | msgstr "" 23 | -------------------------------------------------------------------------------- /locales/eo.po: -------------------------------------------------------------------------------- 1 | # Esperanto translations for puppetlabs.pcp_common package. 2 | # Copyright (C) 2017 Puppet 3 | # This file is distributed under the same license as the puppetlabs.pcp_common package. 4 | # Automatically generated, 2017. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: puppetlabs.pcp_common \n" 9 | "Report-Msgid-Bugs-To: docs@puppet.com\n" 10 | "POT-Creation-Date: \n" 11 | "PO-Revision-Date: \n" 12 | "Last-Translator: Automatically generated\n" 13 | "Language-Team: none\n" 14 | "Language: eo\n" 15 | "MIME-Version: 1.0\n" 16 | "Content-Type: text/plain; charset=UTF-8\n" 17 | "Content-Transfer-Encoding: 8bit\n" 18 | "Plural-Forms: nplurals=2; plural=(n != 1);\n" 19 | 20 | #: src/puppetlabs/pcp/message_v1.clj 21 | msgid "first chunk should be type 1" 22 | msgstr "" 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/puppetlabs/clj-pcp-common.png?branch=master)](https://travis-ci.org/puppetlabs/clj-pcp-common) 2 | 3 | ## clj-pcp-common 4 | 5 | PCP message codec and protocol helpers 6 | 7 | https://github.com/puppetlabs/pcp-specifications 8 | 9 | It supports PCP v1 and v2 via the `message-v1` and `message-v2` namespaces. The `protocol` namespace defines a common 10 | definition for both versions of the protocol; note that some message types have been removed from v2. 11 | 12 | ## Installation 13 | 14 | To use this service in your trapperkeeper application, simply add this 15 | project as a dependency in your leiningen project file: 16 | 17 | [![Clojars Project](http://clojars.org/puppetlabs/pcp-common/latest-version.svg)](http://clojars.org/puppetlabs/pcp-common) 18 | 19 | ## Contributing 20 | 21 | Please refer to [this][contributing] document. 22 | 23 | [contributing]: CONTRIBUTING.md 24 | -------------------------------------------------------------------------------- /test/puppetlabs/pcp/protocol_test.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.protocol-test 2 | (:require [clojure.test :refer :all] 3 | [puppetlabs.pcp.protocol :refer :all] 4 | [puppetlabs.kitchensink.core :as ks] 5 | [schema.core :as s] 6 | [schema.test :as st])) 7 | 8 | (deftest uri-schema-test 9 | (testing "valid uris" 10 | (is (= (s/validate Uri "pcp:///server") "pcp:///server")) 11 | (is (= (s/validate Uri "pcp://bananas/server") "pcp://bananas/server")) 12 | (is (= (s/validate Uri "pcp://shoes/test") "pcp://shoes/test"))) 13 | (testing "invalid uris" 14 | (is (thrown? Exception (s/validate Uri ""))) 15 | (is (thrown? Exception (s/validate Uri "pcp://server"))) 16 | (is (thrown? Exception (s/validate Uri "server"))) 17 | (is (thrown? Exception (s/validate Uri "pcp://test/with/too_many_slashes"))))) 18 | 19 | (deftest explode-uri-test 20 | (testing "It raises on invalid uris" 21 | (is (thrown? Exception (explode-uri "")))) 22 | (testing "It returns component chunks" 23 | (is (= ["localhost" "agent"] (explode-uri "pcp://localhost/agent"))) 24 | (is (= ["localhost" "*"] (explode-uri "pcp://localhost/*"))) 25 | (is (= ["*" "agent"] (explode-uri "pcp://*/agent"))))) 26 | 27 | (deftest uri-wildcard?-test 28 | (is (= ["*" "*"] (uri-wildcard? "pcp://*/*"))) 29 | (is (= ["*" "agent"] (uri-wildcard? "pcp://*/agent"))) 30 | (is (= ["agent01.example.com" "*"] (uri-wildcard? "pcp://agent01.example.com/*"))) 31 | (is (= nil (uri-wildcard? "pcp://agent01.example.com/agent")))) -------------------------------------------------------------------------------- /src/puppetlabs/pcp/message_v2.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.message-v2 2 | (:require [cheshire.core :as cheshire] 3 | [puppetlabs.kitchensink.core :as ks] 4 | [puppetlabs.pcp.protocol :refer [v2-Envelope ISO8601]] 5 | [schema.core :as s] 6 | [slingshot.slingshot :refer [try+ throw+]] 7 | [puppetlabs.i18n.core :as i18n])) 8 | 9 | ;; schemas for message validation 10 | (def Message 11 | "Defines the message objects we're using" 12 | v2-Envelope) 13 | 14 | (s/defn message->envelope :- v2-Envelope 15 | "Returns the map without any of the known 'private' keys. Should 16 | map to an envelope schema." 17 | [message :- Message] 18 | message) 19 | 20 | (s/defn get-data :- s/Any 21 | "Returns the data" 22 | [message :- Message] 23 | (get message :data)) 24 | 25 | (s/defn set-data :- Message 26 | "Sets the data" 27 | [message :- Message data :- s/Any] 28 | (assoc message :data data)) 29 | 30 | (s/defn make-message :- Message 31 | "Returns a new empty message structure" 32 | ([] (make-message {})) 33 | ([k v & kvs] 34 | (make-message (apply hash-map k v kvs))) 35 | ([opts] 36 | (into {:id (ks/uuid) 37 | :message_type ""} 38 | opts))) 39 | 40 | (s/defn ^:always-validate encode :- String 41 | "Returns a text representation of a message for transmission. 42 | Always validates input and output." 43 | [message :- Message] 44 | (cheshire/generate-string (message->envelope message))) 45 | 46 | (s/defn ^:always-validate decode :- Message 47 | "Returns a message object from a text format used for transmission. 48 | Always validates input and output." 49 | [text :- String] 50 | (cheshire/parse-string text true)) 51 | -------------------------------------------------------------------------------- /.github/workflows/mend.yaml: -------------------------------------------------------------------------------- 1 | name: mend_scan 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: connect_twingate 12 | uses: twingate/github-action@v1 13 | with: 14 | service-key: ${{ secrets.TWINGATE_PUBLIC_REPO_KEY }} 15 | - name: checkout repo content 16 | uses: actions/checkout@v2 # checkout the repository content to github runner. 17 | with: 18 | fetch-depth: 1 19 | # install java which is required for mend and clojure 20 | - name: setup java 21 | uses: actions/setup-java@v3 22 | with: 23 | distribution: temurin 24 | java-version: 17 25 | # install clojure tools 26 | - name: Install Clojure tools 27 | uses: DeLaGuardo/setup-clojure@10.1 28 | with: 29 | # Install just one or all simultaneously 30 | # The value must indicate a particular version of the tool, or use 'latest' 31 | # to always provision the latest version 32 | cli: latest # Clojure CLI based on tools.deps 33 | lein: latest # Leiningen 34 | boot: latest # Boot.clj 35 | bb: latest # Babashka 36 | clj-kondo: latest # Clj-kondo 37 | cljstyle: latest # cljstyle 38 | zprint: latest # zprint 39 | # run lein gen 40 | - name: create pom.xml 41 | run: lein pom 42 | # download mend 43 | - name: download_mend 44 | run: curl -o wss-unified-agent.jar https://unified-agent.s3.amazonaws.com/wss-unified-agent.jar 45 | - name: run mend 46 | run: env WS_INCLUDES=pom.xml java -jar wss-unified-agent.jar 47 | env: 48 | WS_APIKEY: ${{ secrets.MEND_API_KEY }} 49 | WS_WSS_URL: https://saas-eu.whitesourcesoftware.com/agent 50 | WS_USERKEY: ${{ secrets.MEND_TOKEN }} 51 | WS_PRODUCTNAME: puppet-foss 52 | WS_PROJECTNAME: ${{ github.event.repository.name }} 53 | WS_FILESYSTEMSCAN: true 54 | WS_CHECKPOLICIES: true 55 | WS_FORCEUPDATE: true 56 | -------------------------------------------------------------------------------- /test/puppetlabs/pcp/message_v2_test.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.message-v2-test 2 | (:require [clojure.test :refer :all] 3 | [puppetlabs.pcp.message-v2 :refer :all] 4 | [slingshot.test] 5 | [schema.core :as s] 6 | [schema.test :as st])) 7 | 8 | (deftest make-message-test 9 | (testing "the created message is a Message" 10 | (is (s/validate Message (make-message)))) 11 | (testing "it makes a message" 12 | (is (= {:message_type ""} 13 | (dissoc (make-message) :id)))) 14 | (testing "it makes a message with a map of parameters" 15 | (let [message (make-message {:sender "pcp://client01.example.com/test" 16 | :target "pcp:///server"})] 17 | (is (= {:message_type "" 18 | :sender "pcp://client01.example.com/test" 19 | :target "pcp:///server"} 20 | (dissoc message :id))))) 21 | (testing "it makes a message with parameters" 22 | (let [message (make-message :sender "pcp://client01.example.com/test" 23 | :target "pcp:///server")] 24 | (is (= {:message_type "" 25 | :sender "pcp://client01.example.com/test" 26 | :target "pcp:///server"} 27 | (dissoc message :id)))))) 28 | 29 | (deftest set-get-data-test 30 | (testing "it gets and sets the data frame" 31 | (let [message (set-data (make-message) {:some "data"})] 32 | (is (= (get-data message) 33 | {:some "data"}))))) 34 | 35 | (deftest encode-test 36 | (with-redefs [puppetlabs.kitchensink.core/uuid (constantly "b9835b34-52d0-4f81-b026-a3941333e082")] 37 | (testing "it encodes a message" 38 | (is (= "{\"id\":\"b9835b34-52d0-4f81-b026-a3941333e082\",\"message_type\":\"\",\"data\":[1,2,3]}" 39 | (encode (set-data (make-message) [1 2 3]))))))) 40 | 41 | (deftest decode-test 42 | (testing "data is accessible" 43 | (is (= [1 2 3] 44 | (get-data (decode "{\"data\":[1,2,3],\"id\":\"b9835b34-52d0-4f81-b026-a3941333e082\",\"message_type\":\"\"}")))))) 45 | 46 | (deftest encoder-roundtrip-test 47 | (testing "it can roundtrip messages" 48 | (let [message (set-data (make-message {:sender "pcp://client01.example.com/test"}) "results")] 49 | (is (= message 50 | (decode (encode message))))))) 51 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject puppetlabs/pcp-common "1.3.7-SNAPSHOT" 2 | :description "Common protocol components for PCP" 3 | :url "https://github.com/puppetlabs/clj-pcp-common" 4 | :license {:name "Apache License, Version 2.0" 5 | :url "http://www.apache.org/licenses/LICENSE-2.0.html"} 6 | 7 | :min-lein-version "2.7.1" 8 | 9 | ;; Abort when version ranges or version conflicts are detected in 10 | ;; dependencies. Also supports :warn to simply emit warnings. 11 | ;; requires lein 2.2.0+. 12 | :pedantic? :abort 13 | 14 | :parent-project {:coords [puppetlabs/clj-parent "4.9.1"] 15 | :inherit [:managed-dependencies]} 16 | 17 | :dependencies [[org.clojure/clojure] 18 | [org.clojure/tools.logging] 19 | [puppetlabs/kitchensink] 20 | [cheshire] 21 | [prismatic/schema] 22 | 23 | [org.clojars.smee/binary "0.3.0"] 24 | 25 | ;; try+/throw+ 26 | [slingshot] 27 | [puppetlabs/i18n]] 28 | 29 | :plugins [[lein-parent "0.3.4"] 30 | [lein-release "1.0.5" :exclusions [org.clojure/clojure]] 31 | [puppetlabs/i18n "0.8.0"]] 32 | 33 | :profiles {:cljfmt {:plugins [[lein-cljfmt "0.5.7" :exclusions [org.clojure/clojure]] 34 | [lein-parent "0.3.4"]] 35 | :parent-project {:path "../pl-clojure-style/project.clj" 36 | :inherit [:cljfmt]}} 37 | :test-base {:test-paths ["test"]} 38 | :test-schema-validation [:test-base 39 | {:injections [(do 40 | (require 'schema.core) 41 | (schema.core/set-fn-validation! true))]}]} 42 | 43 | :aliases {"cljfmt" ["with-profile" "+cljfmt" "cljfmt"] 44 | "test-all" ["with-profile" "test-base:test-schema-validation" "test"]} 45 | 46 | :deploy-repositories [["releases" {:url "https://clojars.org/repo" 47 | :username :env/clojars_jenkins_username 48 | :password :env/clojars_jenkins_password 49 | :sign-releases false}]] 50 | 51 | :lein-release {:scm :git 52 | :deploy-via :lein-deploy}) 53 | -------------------------------------------------------------------------------- /src/puppetlabs/pcp/protocol.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.protocol 2 | (:require [clojure.string :as str] 3 | [puppetlabs.kitchensink.core :as ks] 4 | [schema.core :as s])) 5 | 6 | (def ISO8601 7 | "Schema validates if string conforms to ISO8601" 8 | (s/pred ks/datetime? 'datetime?)) 9 | 10 | (def Uri 11 | "Schema for PCP node Uri" 12 | (s/pred (partial re-matches #"^pcp://[^/]*/[^/]+$") 'uri?)) 13 | 14 | (def ExplodedUri 15 | "Schema for PCP node Exploded Uri - an Uri split into the client and type components" 16 | (s/pair s/Str "client" s/Str "type")) 17 | 18 | (def InventoryChange 19 | "Schema for a single change in inventory record" 20 | {:client Uri :change (s/enum -1 1)}) 21 | 22 | (def MessageId 23 | "A message identifier, as a string" 24 | (s/pred ks/uuid?)) 25 | 26 | (def v2-Envelope 27 | "Defines the envelope format of a v2 message" 28 | {:id MessageId 29 | :message_type s/Str 30 | (s/optional-key :target) Uri 31 | (s/optional-key :sender) Uri 32 | (s/optional-key :in_reply_to) MessageId 33 | (s/optional-key :data) s/Any}) 34 | 35 | (def v1-Envelope 36 | "Defines the envelope format of a v1 message" 37 | {:id MessageId 38 | (s/optional-key :in-reply-to) MessageId 39 | :sender Uri 40 | :targets [Uri] 41 | :message_type s/Str 42 | :expires ISO8601 43 | (s/optional-key :destination_report) s/Bool}) 44 | 45 | (def AssociateResponse 46 | "Schema for http://puppetlabs.com/associate_response" 47 | {:id MessageId 48 | :success s/Bool 49 | (s/optional-key :reason) s/Str}) 50 | 51 | (def InventoryRequest 52 | "Data schema for http://puppetlabs.com/inventory_request" 53 | {:query [Uri] 54 | (s/optional-key :subscribe) s/Bool}) 55 | 56 | (def InventoryResponse 57 | "Data schema for http://puppetlabs.com/inventory_response" 58 | {:uris [Uri]}) 59 | 60 | (def InventoryUpdate 61 | "Data schema for http://puppetlabs.com/inventory_update" 62 | {:changes [InventoryChange]}) 63 | 64 | (def DestinationReport 65 | "Defines the data field for a destination report body" 66 | {:id MessageId 67 | :targets [Uri]}) 68 | 69 | (def ErrorMessage 70 | "Data schema for http://puppetlabs.com/error_message" 71 | {(s/optional-key :id) MessageId 72 | :description s/Str}) 73 | 74 | (def v2-ErrorMessage 75 | "Data schema for http://puppetlabs.com/error_message" 76 | s/Str) 77 | 78 | (def TTLExpiredMessage 79 | "Data schema for http://puppetlabs.com/ttl_expired" 80 | {:id MessageId}) 81 | 82 | (def VersionErrorMessage 83 | "Data schema for http://puppetlabs.com/version_error" 84 | {:id MessageId 85 | :target s/Str 86 | :reason s/Str}) 87 | 88 | (def DebugChunk 89 | "Data schema for a debug chunk" 90 | {:hops [{(s/required-key :server) Uri 91 | (s/optional-key :stage) s/Str 92 | (s/required-key :time) ISO8601}]}) 93 | 94 | (s/defn explode-uri :- ExplodedUri 95 | "Parse an Uri string into its component parts. Raises if incomplete" 96 | [uri :- Uri] 97 | (str/split (subs uri 6) #"/")) 98 | 99 | (s/defn uri-wildcard? :- (s/maybe ExplodedUri) 100 | [uri :- Uri] 101 | (let [chunks (explode-uri uri)] 102 | (if (some (partial = "*") chunks) 103 | chunks))) 104 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.3.4 2 | 3 | This is a maintenance release. 4 | 5 | * update clj-parent to 4.9.1 6 | 7 | ## 1.3.3 8 | 9 | This is a maintenance release. 10 | 11 | * update clj-parent to 4.6.17 12 | 13 | 14 | ## 1.3.2 15 | 16 | This is a maintenance release. 17 | 18 | * update clj-parent to 4.6.14 19 | 20 | ## 1.3.1 21 | 22 | This is a maintenance release. 23 | 24 | * update clj-parent to 4.4.1 25 | 26 | 27 | ## 1.3.0 28 | 29 | This is a maintenance release. 30 | 31 | * update clj-parent to 3.1.1 32 | * remove implementation of uuid? If an alternative is needed, use kitchensink.core/uuid? 33 | 34 | ## 1.2.0 35 | 36 | This is a feature release. 37 | 38 | * Add support for Java 9. 39 | 40 | ## 1.1.4 41 | 42 | This is a maintenance release 43 | 44 | * Bumps clj-parent to 0.6.1, with i18n 0.8.0. 45 | 46 | ## 1.1.3 47 | 48 | This is a maintenance release 49 | 50 | * [PCP-731](https://tickets.puppetlabs.com/browse/PCP-731) Bump clj-parent to 51 | 0.4.3 for i18n 0.7.1. 52 | 53 | ## 1.1.2 54 | 55 | This is a maintenance release. 56 | 57 | * [PCP-731](https://tickets.puppetlabs.com/browse/PCP-731) Bump i18n to 0.7.0 58 | to pickup a change in pot file name. 59 | * Bump clj-parent to 0.4.1. 60 | 61 | ## 1.1.1 62 | 63 | This is a maintenance release. 64 | 65 | * Add a schema for the PCP v2 ErrorMessage, which did not previously match the 66 | specification. 67 | 68 | ## 1.1.0 69 | 70 | This is a feature release. 71 | 72 | * [PCP-600](https://tickets.puppetlabs.com/browse/PCP-600) Add schema 73 | definitions to be used in inventory updates. Additionally changes the 74 | return value of `uri-wildcard?` to be the exploded Uri in case it is a 75 | wildcard, or nil otherwise; this should not impact truthiness of the value. 76 | * Bump clj-parent to 0.3.2 77 | 78 | ## 1.0.0 79 | 80 | This is a major feature release introducing PCP v2. It continues to support PCP 81 | v1, but breaks API compatibility for those using this library. 82 | 83 | * [PCP-645](https://tickets.puppetlabs.com/browse/PCP-645) Add PCP v2 protocol 84 | 85 | ## 0.5.5 86 | 87 | This is a maintenance release 88 | 89 | * [PCP-620](https://tickets.puppetlabs.com/browse/PCP-620) Validate chunk 90 | lengths when decoding to prevent DOS 91 | 92 | ## 0.5.4 93 | 94 | This is a maintenance release 95 | 96 | * Updates clj-i18n to 0.4.3 for a bug introduced in 0.4.2 97 | 98 | ## 0.5.3 99 | 100 | This is a maintenance release 101 | 102 | * Updates clj-i18n to 0.4.2 for a performance-related bug fix 103 | 104 | ## 0.5.2 105 | 106 | This is a maintenance release 107 | 108 | * [PCP-525](https://tickets.puppetlabs.com/browse/PCP-525) Explicitly 109 | validate the Message argument of the message/encode function. 110 | * [PCP-535](https://tickets.puppetlabs.com/browse/PCP-535) Don't run tests 111 | with schema validation enabled. 112 | * [PR #26](https://github.com/puppetlabs/clj-pcp-common/pull/26) Update 113 | dependencies to be consistent with upstream projects. 114 | 115 | ## 0.5.1 116 | 117 | This is a maintenance release 118 | 119 | * [PCP-367](https://tickets.puppetlabs.com/browse/PCP-367) Add i18n library 120 | and mark text strings for extraction. 121 | * [PCP-467](https://tickets.puppetlabs.com/browse/PCP-467) Disable Prismatic 122 | Schema validation by default. 123 | * [PCP-483](https://tickets.puppetlabs.com/browse/PCP-483) Fix InventoryRequest 124 | schema. It was overly broad in relation to the definition at 125 | pcp-specifications. 126 | 127 | ## 0.5.0 128 | 129 | This is a feature release. 130 | 131 | This is the first public release to clojars. 132 | 133 | * [PCP-42](https://tickets.puppetlabs.com/browse/PCP-42) Added schema for 134 | `http://puppetlabs.com/version_error` message bodies. 135 | * [PCP-45](https://tickets.puppetlabs.com/browse/PCP-45) Release to clojars 136 | rather than internal nexus servers. 137 | 138 | ## 0.4.1 139 | 140 | This is a maintenance release 141 | 142 | * [CTH-311](https://tickets.puppetlabs.com/browse/CTH-311) Updated 143 | Uri scheme from `cth` to `pcp` 144 | 145 | ## 0.4.0 146 | 147 | * Renamed from former codenames to new component names. 148 | 149 | ## 0.2.0 150 | 151 | * Removed server state from Message (CTH-328) 152 | * Removed add-hops function 153 | * Added add-debug add-json-debug functions 154 | * Now verify that MessageId looks like a uuid 155 | 156 | ## 0.1.0 157 | 158 | * Added prismatic schema schema.core/defn decorations to the rest of 159 | the public api functions (CTH-206) 160 | * Renamed Endpoint -> Uri, and reworked envelope schema for changes to 161 | cthun specifications (CTH-210) 162 | 163 | ## 0.0.1 164 | 165 | * Initial internal release, extracted from cthun server (CTH-185) 166 | * Added set-expiry 167 | * Added Message schema and made make-message constrain to it. 168 | -------------------------------------------------------------------------------- /dev-resources/Makefile.i18n: -------------------------------------------------------------------------------- 1 | # -*- Makefile -*- 2 | # This file was generated by the i18n leiningen plugin 3 | # Do not edit this file; it will be overwritten the next time you run 4 | # lein i18n init 5 | # 6 | 7 | # The name of the package into which the translations bundle will be placed 8 | BUNDLE=puppetlabs.pcp_common 9 | 10 | # The name of the POT file into which the gettext code strings (msgid) will be placed 11 | POT_NAME=pcp-common.pot 12 | 13 | # The list of names of packages covered by the translation bundle; 14 | # by default it contains a single package - the same where the translations 15 | # bundle itself is placed - but this can be overridden - preferably in 16 | # the top level Makefile 17 | PACKAGES?=$(BUNDLE) 18 | LOCALES=$(basename $(notdir $(wildcard locales/*.po))) 19 | BUNDLE_DIR=$(subst .,/,$(BUNDLE)) 20 | BUNDLE_FILES=$(patsubst %,resources/$(BUNDLE_DIR)/Messages_%.class,$(LOCALES)) 21 | FIND_SOURCES=find src -name \*.clj 22 | # xgettext before 0.19 does not understand --add-location=file. Even CentOS 23 | # 7 ships with an older gettext. We will therefore generate full location 24 | # info on those systems, and only file names where xgettext supports it 25 | LOC_OPT=$(shell xgettext --add-location=file -f - /dev/null 2>&1 && echo --add-location=file || echo --add-location) 26 | 27 | LOCALES_CLJ=resources/locales.clj 28 | define LOCALES_CLJ_CONTENTS 29 | { 30 | :locales #{$(patsubst %,"%",$(LOCALES))} 31 | :packages [$(patsubst %,"%",$(PACKAGES))] 32 | :bundle $(patsubst %,"%",$(BUNDLE).Messages) 33 | } 34 | endef 35 | export LOCALES_CLJ_CONTENTS 36 | 37 | 38 | i18n: msgfmt 39 | 40 | # Update locales/.pot 41 | update-pot: locales/$(POT_NAME) 42 | 43 | locales/$(POT_NAME): $(shell $(FIND_SOURCES)) | locales 44 | @tmp=$$(mktemp $@.tmp.XXXX); \ 45 | $(FIND_SOURCES) \ 46 | | xgettext --from-code=UTF-8 --language=lisp \ 47 | --copyright-holder='Puppet ' \ 48 | --package-name="$(BUNDLE)" \ 49 | --package-version="$(BUNDLE_VERSION)" \ 50 | --msgid-bugs-address="docs@puppet.com" \ 51 | -k \ 52 | -kmark:1 -ki18n/mark:1 \ 53 | -ktrs:1 -ki18n/trs:1 \ 54 | -ktru:1 -ki18n/tru:1 \ 55 | -ktrun:1,2 -ki18n/trun:1,2 \ 56 | -ktrsn:1,2 -ki18n/trsn:1,2 \ 57 | $(LOC_OPT) \ 58 | --add-comments --sort-by-file \ 59 | -o $$tmp -f -; \ 60 | sed -i.bak -e 's/charset=CHARSET/charset=UTF-8/' $$tmp; \ 61 | sed -i.bak -e 's/POT-Creation-Date: [^\\]*/POT-Creation-Date: /' $$tmp; \ 62 | rm -f $$tmp.bak; \ 63 | if ! diff -q -I POT-Creation-Date $$tmp $@ >/dev/null 2>&1; then \ 64 | mv $$tmp $@; \ 65 | else \ 66 | rm $$tmp; touch $@; \ 67 | fi 68 | 69 | # Run msgfmt over all .po files to generate Java resource bundles 70 | # and create the locales.clj file 71 | msgfmt: $(BUNDLE_FILES) $(LOCALES_CLJ) clean-orphaned-bundles 72 | 73 | # Force rebuild of locales.clj if its contents is not the the desired one. The 74 | # shell echo is used to add a trailing newline to match the one from `cat` 75 | ifneq ($(shell cat $(LOCALES_CLJ) 2> /dev/null),$(shell echo '$(LOCALES_CLJ_CONTENTS)')) 76 | .PHONY: $(LOCALES_CLJ) 77 | endif 78 | $(LOCALES_CLJ): | resources 79 | @echo "Writing $@" 80 | @echo "$$LOCALES_CLJ_CONTENTS" > $@ 81 | 82 | # Remove every resource bundle that wasn't generated from a PO file. 83 | # We do this because we used to generate the english bundle directly from the POT. 84 | .PHONY: clean-orphaned-bundles 85 | clean-orphaned-bundles: 86 | @for bundle in resources/$(BUNDLE_DIR)/Messages_*.class; do \ 87 | locale=$$(basename "$$bundle" | sed -E -e 's/\$$?1?\.class$$/_class/' | cut -d '_' -f 2;); \ 88 | if [ ! -f "locales/$$locale.po" ]; then \ 89 | rm "$$bundle"; \ 90 | fi \ 91 | done 92 | 93 | resources/$(BUNDLE_DIR)/Messages_%.class: locales/%.po | resources 94 | msgfmt --java2 -d resources -r $(BUNDLE).Messages -l $(*F) $< 95 | 96 | # Use this to initialize translations. Updating the PO files is done 97 | # automatically through a CI job that utilizes the scripts in the project's 98 | # `bin` file, which themselves come from the `clj-i18n` project. 99 | locales/%.po: | locales 100 | @if [ ! -f $@ ]; then \ 101 | touch $@ && msginit --no-translator -l $(*F) -o $@ -i locales/$(POT_NAME); \ 102 | fi 103 | 104 | resources locales: 105 | @mkdir $@ 106 | 107 | help: 108 | $(info $(HELP)) 109 | @echo 110 | 111 | .PHONY: help 112 | 113 | define HELP 114 | This Makefile assists in handling i18n related tasks during development. Files 115 | that need to be checked into source control are put into the locales/ directory. 116 | They are 117 | 118 | locales/$(POT_NAME) - the POT file generated by 'make update-pot' 119 | locales/$$LANG.po - the translations for $$LANG 120 | 121 | Only the $$LANG.po files should be edited manually; this is usually done by 122 | translators. 123 | 124 | You can use the following targets: 125 | 126 | i18n: refresh all the files in locales/ and recompile resources 127 | update-pot: extract strings and update locales/$(POT_NAME) 128 | locales/LANG.po: create translations for LANG 129 | msgfmt: compile the translations into Java classes; this step is 130 | needed to make translations available to the Clojure code 131 | and produces Java class files in resources/ 132 | endef 133 | # @todo lutter 2015-04-20: for projects that use libraries with their own 134 | # translation, we need to combine all their translations into one big po 135 | # file and then run msgfmt over that so that we only have to deal with one 136 | # resource bundle 137 | -------------------------------------------------------------------------------- /test/puppetlabs/pcp/message_v1_test.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.message-v1-test 2 | (:require [clojure.test :refer :all] 3 | [puppetlabs.pcp.message-v1 :refer :all] 4 | [slingshot.test] 5 | [schema.core :as s] 6 | [schema.test :as st])) 7 | 8 | (deftest byte-array-conversion-test 9 | (testing "byte array round trip conversion" 10 | (is (= "☃" (-> "☃" string->bytes bytes->string))))) 11 | 12 | (deftest make-message-test 13 | (testing "the created message is a Message" 14 | (is (s/validate Message (make-message)))) 15 | (testing "it makes a message" 16 | (is (= {:sender "" 17 | :targets [] 18 | :expires "1970-01-01T00:00:00.000Z" 19 | :message_type ""} 20 | (dissoc (make-message) :_chunks :id)))) 21 | (testing "it makes a message with a map of parameters" 22 | (let [message (make-message {:sender "pcp://client01.example.com/test" 23 | :targets ["pcp:///server"]})] 24 | (is (= {:sender "pcp://client01.example.com/test" 25 | :targets ["pcp:///server"] 26 | :expires "1970-01-01T00:00:00.000Z" 27 | :message_type ""} 28 | (dissoc message :_chunks :id))))) 29 | (testing "it makes a message with parameters" 30 | (let [message (make-message :sender "pcp://client01.example.com/test" 31 | :targets ["pcp:///server"])] 32 | (is (= {:sender "pcp://client01.example.com/test" 33 | :targets ["pcp:///server"] 34 | :expires "1970-01-01T00:00:00.000Z" 35 | :message_type ""} 36 | (dissoc message :_chunks :id)))))) 37 | 38 | (deftest set-expiry-test 39 | (testing "it sets expiries to what you tell it" 40 | (is (= (:expires (set-expiry (make-message) "1971-01-01T00:00:00.000Z")) "1971-01-01T00:00:00.000Z"))) 41 | (testing "it supports relative time" 42 | ;; Hello future test debugger. At one point someone said "we 43 | ;; should never be 3 seconds before the epoch". Past test writer 44 | ;; needs a slap. 45 | (is (not (= (:expires (set-expiry (make-message) 3 :seconds)) "1970-01-01T00:00:00.000Z"))))) 46 | 47 | (deftest get-data-test 48 | (testing "it returns data from the data frame" 49 | (let [message (set-data (make-message) (byte-array [4 6 2]))] 50 | (is (= [4 6 2] 51 | (vec (get-data message))))))) 52 | 53 | (deftest set-data-test 54 | (testing "it sets the data frame" 55 | (let [message (set-data (make-message) (byte-array [1 2 3]))] 56 | (is (= (vec (get-data message)) 57 | [1 2 3]))))) 58 | 59 | (deftest get-json-data-test 60 | (testing "it json decodes the data frame" 61 | (let [message (set-data (make-message) (string->bytes "{}"))] 62 | (is (= (get-json-data message) {}))))) 63 | 64 | (deftest set-json-data-test 65 | (testing "it json encodes to the data frame" 66 | (let [message (set-json-data (make-message) {})] 67 | (is (= (bytes->string (get-data message)) 68 | "{}"))))) 69 | 70 | (deftest encode-descriptor-test 71 | (testing "it encodes" 72 | (is (= 1 73 | (encode-descriptor {:type 1}))) 74 | (is (= 2r10000001 75 | (encode-descriptor {:type 1 :flags #{:unused1}}))) 76 | (is (= 2r10010001 77 | (encode-descriptor {:type 1 :flags #{:unused1 :unused4}}))))) 78 | 79 | (deftest decode-descriptor-test 80 | (testing "it decodes" 81 | (is (= {:type 1 :flags #{}} 82 | (decode-descriptor 1))) 83 | (is (= {:type 1 :flags #{:unused1}} 84 | (decode-descriptor 2r10000001))) 85 | (is (= {:type 1 :flags #{:unused1 :unused4}} 86 | (decode-descriptor 2r10010001))))) 87 | 88 | (deftest encode-test 89 | (testing "when being strict, we take a Message only" 90 | (is (thrown+? [:type :schema.core/error] 91 | (encode {})) 92 | "Rejected an empty map as a Message")) 93 | ;; don't include the envelope in the encoded messages in the following 94 | ;; tests for the sake of brevity 95 | (with-redefs [message->envelope (constantly {})] 96 | (testing "it returns a byte array" 97 | ;; subsequent tests will use vec to ignore this 98 | (is (= (class (byte-array 0)) 99 | (class (encode (make-message)))))) 100 | (testing "it encodes a message" 101 | (is (= [1, ; PCP version 102 | 1, 0 0 0 2, 123 125, ; envelope chunk: chunk type, content size, content 103 | 2, 0 0 0 0] ; data chunk: chunk type, content size 104 | (vec (encode (make-message)))))) 105 | (testing "it adds debug type as an optional final chunk" 106 | (is (= [1, ; PCP version 107 | 1, 0 0 0 2, 123 125, ; envelope chunk 108 | 2, 0 0 0 0, ; data chunk 109 | 3, 0 0 0 4, 115 111 109 101] ; debug chunk: chunk type, content size, content 110 | (vec (encode (set-debug (make-message) (string->bytes "some"))))))) 111 | (testing "it encodes the data chunk" 112 | (is (= [1, 113 | 1, 0 0 0 2, 123 125, 114 | 2, 0 0 0 4, 104 97 104 97] 115 | (vec (encode (set-data (make-message) (string->bytes "haha"))))))))) 116 | 117 | (deftest decode-test 118 | (testing "it only handles version 1 messages" 119 | (is (thrown+? [:type :puppetlabs.pcp.message-v1/message-malformed] 120 | (decode (byte-array [2]))))) 121 | (testing "it insists on envelope chunk first" 122 | (is (thrown+? [:type :puppetlabs.pcp.message-v1/message-invalid] 123 | (decode (byte-array [1, 124 | 2, 0 0 0 2, 123 125]))))) 125 | (testing "it insists on a well-formed envelope" 126 | (is (thrown+? [:type :puppetlabs.pcp.message-v1/envelope-malformed] 127 | (decode (byte-array [1, 128 | 1, 0 0 0 1, 123]))))) 129 | (testing "it insists on a complete envelope" 130 | (is (thrown+? [:type :puppetlabs.pcp.message-v1/envelope-invalid] 131 | (decode (byte-array [1, 132 | 1, 0 0 0 2, 123 125]))))) 133 | (testing "it validates the chunk lengths" 134 | (is (thrown+-with-msg? [:type :puppetlabs.pcp.message-v1/message-malformed] 135 | #":message \"Invalid chunk length: -1 \(should be between 0 and 13\)\"" 136 | (decode (byte-array [1, 137 | 1, 0 0 0 2, 123 125, 138 | 2, -1 -1 -1 -1])))) 139 | (is (thrown+-with-msg? [:type :puppetlabs.pcp.message-v1/message-malformed] 140 | #":message \"Invalid chunk length: 5000 \(should be between 0 and 14\)\"" 141 | (decode (byte-array [1, 142 | 1, 0 0 0 2, 123 125, 143 | 2, 0 0 19 136, 0]))))) 144 | ;; disable schema validations (both signature validations and explicit 145 | ;; calls to `schema.core/validate`) for the following tests as the byte 146 | ;; arrays used in them don't match the expected schemas for the sake 147 | ;; of brevity 148 | (s/without-fn-validation 149 | (with-redefs [schema.core/validate (fn [_ v] v)] 150 | (testing "it decodes the null message" 151 | (is (= (dissoc (message->envelope (make-message)) :id) 152 | (dissoc (message->envelope (decode (byte-array [1, 1, 0 0 0 2, 123 125]))) :id)))) 153 | (testing "data is accessible" 154 | (let [message (decode (byte-array [1, 155 | 1, 0 0 0 2, 123 125, 156 | 2, 0 0 0 3, 108 111 108]))] 157 | (is (= "lol" (String. (get-data message)))))) 158 | (testing "debug is accessible" 159 | (let [message (decode (byte-array [1, 160 | 1, 0 0 0 2, 123 125, 161 | 2, 0 0 0 0, 162 | 3, 0 0 0 3, 108 111 108]))] 163 | (is (= "lol" (String. (get-debug message))))))))) 164 | 165 | (deftest encoder-roundtrip-test 166 | (testing "it can roundtrip data" 167 | (let [data (byte-array (map byte "hola")) 168 | encoded (encode (set-data (make-message {:sender "pcp://client01.example.com/test"}) data)) 169 | decoded (decode encoded)] 170 | (is (= (vec (get-data decoded)) 171 | (vec data)))))) 172 | -------------------------------------------------------------------------------- /src/puppetlabs/pcp/message_v1.clj: -------------------------------------------------------------------------------- 1 | (ns puppetlabs.pcp.message-v1 2 | (:require [org.clojars.smee.binary.core :as b] 3 | [cheshire.core :as cheshire] 4 | [clj-time.core :as t] 5 | [clj-time.format :as tf] 6 | [puppetlabs.kitchensink.core :as ks] 7 | [puppetlabs.pcp.protocol :refer [v1-Envelope ISO8601]] 8 | [schema.core :as s] 9 | [slingshot.slingshot :refer [try+ throw+]] 10 | [puppetlabs.i18n.core :as i18n]) 11 | (:import [java.nio.charset Charset])) 12 | 13 | ;; schemas for message validation 14 | (def Message 15 | "Defines the message objects we're using" 16 | ;; NOTE(richardc) the overriding of :sender here is a bit janky, we 17 | ;; accept that we can have anything in memory, but we'll check the 18 | ;; Envelope schema when interacting with the network 19 | (merge v1-Envelope 20 | {:sender s/Str 21 | :_chunks {s/Keyword s/Any}})) 22 | 23 | (def ByteArray 24 | "Schema for a byte-array" 25 | bytes) 26 | 27 | (def ^:private empty-byte-array 28 | (byte-array 0)) 29 | 30 | (def FlagSet 31 | "Schema for the message flags" 32 | #{s/Keyword}) 33 | 34 | ;; string <-> byte-array utilities 35 | 36 | (def ^Charset conversion-charset 37 | "Charset used for the string <-> byte-array conversions" 38 | (Charset/forName "UTF-8")) 39 | 40 | (defn ^bytes string->bytes 41 | "Returns an array of bytes from a string" 42 | [^String s] 43 | (.getBytes s conversion-charset)) 44 | 45 | (defn ^String bytes->string 46 | "Returns a string given a byte-array" 47 | [^bytes bytes] 48 | (String. bytes conversion-charset)) 49 | 50 | ;; abstract message manipulation 51 | (s/defn message->envelope :- v1-Envelope 52 | "Returns the map without any of the known 'private' keys. Should 53 | map to an envelope schema." 54 | [message :- Message] 55 | (dissoc message :_chunks)) 56 | 57 | (defn filter-private 58 | "Deprecated, use message->envelope if you need" 59 | {:deprecated "0.2.0"} 60 | [message] (message->envelope message)) 61 | 62 | (s/defn set-expiry :- Message 63 | "Returns a message with new expiry" 64 | ([message :- Message number :- s/Int unit :- s/Keyword] 65 | (let [expiry (condp = unit 66 | :seconds (t/from-now (t/seconds number)) 67 | :hours (t/from-now (t/hours number)) 68 | :days (t/from-now (t/days number))) 69 | expires (tf/unparse (tf/formatters :date-time) expiry)] 70 | (set-expiry message expires))) 71 | ([message :- Message timestamp :- ISO8601] 72 | (assoc message :expires timestamp))) 73 | 74 | (s/defn get-data :- ByteArray 75 | "Returns the data from the data frame" 76 | [message :- Message] 77 | (get-in message [:_chunks :data :data] empty-byte-array)) 78 | 79 | (s/defn get-debug :- ByteArray 80 | "Returns the data from the debug frame" 81 | [message :- Message] 82 | (get-in message [:_chunks :debug :data] empty-byte-array)) 83 | 84 | (s/defn set-data :- Message 85 | "Sets the data for the data frame" 86 | ([message :- Message data :- ByteArray] (set-data message data #{})) 87 | ([message :- Message data :- ByteArray flags :- FlagSet] 88 | (assoc-in message [:_chunks :data] {:descriptor {:type 2 89 | :flags flags} 90 | :data data}))) 91 | 92 | (s/defn set-debug :- Message 93 | "Sets the data for the debug frame" 94 | ([message :- Message data :- ByteArray] (set-debug message data #{})) 95 | ([message :- Message data :- ByteArray flags :- FlagSet] 96 | (assoc-in message [:_chunks :debug] {:descriptor {:type 3 97 | :flags flags} 98 | :data data}))) 99 | 100 | (s/defn get-json-data :- s/Any 101 | "Returns the data from the data frame decoded from json" 102 | [message :- Message] 103 | (-> (get-data message) 104 | bytes->string 105 | (cheshire/parse-string true))) 106 | 107 | (s/defn get-json-debug :- s/Any 108 | "Returns the data from the debug frame decoded from json" 109 | [message :- Message] 110 | (-> (get-debug message) 111 | bytes->string 112 | (cheshire/parse-string true))) 113 | 114 | (s/defn set-json-data :- Message 115 | "Sets the data to be the json byte-array version of data" 116 | [message :- Message data :- s/Any] 117 | (set-data message (string->bytes (cheshire/generate-string data)))) 118 | 119 | (s/defn set-json-debug :- Message 120 | "Sets the debug data to be the json byte-array version of data" 121 | [message :- Message data :- s/Any] 122 | (set-debug message (string->bytes (cheshire/generate-string data)))) 123 | 124 | (s/defn make-message :- Message 125 | "Returns a new empty message structure" 126 | ([] (make-message {})) 127 | ([k v & kvs] 128 | (make-message (apply hash-map k v kvs))) 129 | ([opts] 130 | (let [message (into {:id (ks/uuid) 131 | :targets [] 132 | :message_type "" 133 | :sender "" 134 | :expires "1970-01-01T00:00:00.000Z" 135 | :_chunks {}} 136 | opts)] 137 | (set-data message empty-byte-array)))) 138 | 139 | ;; message encoding/codecs 140 | 141 | (def flag-bits 142 | {2r1000 :unused1 143 | 2r0100 :unused2 144 | 2r0010 :unused3 145 | 2r0001 :unused4}) 146 | 147 | ;; a var which is bound to the PCP message's length before its decoding 148 | ;; the value is used to validate the lengths of the PCP message chunks 149 | (def ^:private ^:dynamic *message-data-length*) 150 | 151 | (defn encode-descriptor 152 | "Returns a binary representation of a chunk descriptor" 153 | [type] 154 | (let [type-bits (:type type) 155 | flag-set (:flags type) 156 | flags (apply bit-or 0 0 (remove nil? (map (fn [[mask name]] (if (contains? flag-set name) mask)) flag-bits))) 157 | byte (bit-or type-bits (bit-shift-left flags 4))] 158 | byte)) 159 | 160 | (defn decode-descriptor 161 | "Returns the clojure object for a chunk descriptor from a byte" 162 | [byte] 163 | (let [type (bit-and 0x0F byte) 164 | flags (bit-shift-right (bit-and 0xF0 byte) 4) 165 | flag-set (into #{} (remove nil? (map (fn [[mask name]] (if (= mask (bit-and mask flags)) name)) flag-bits)))] 166 | {:flags flag-set 167 | :type type})) 168 | 169 | (def descriptor-codec 170 | (b/compile-codec :byte encode-descriptor decode-descriptor)) 171 | 172 | (def length-codec 173 | (b/compile-codec :int-be 174 | identity 175 | (fn [l] 176 | (if (or (neg? l) (>= l *message-data-length*)) 177 | (throw 178 | (IllegalArgumentException. 179 | (str "Invalid chunk length: " l " (should be between 0 and " *message-data-length* ")")))) 180 | l))) 181 | 182 | (def chunk-codec 183 | (b/ordered-map 184 | :descriptor descriptor-codec 185 | :data (b/blob :prefix length-codec))) 186 | 187 | (def message-codec 188 | (b/ordered-map 189 | :version (b/constant :byte 1) 190 | :chunks (b/repeated chunk-codec))) 191 | 192 | (s/defn encode :- ByteArray 193 | [message :- Message] 194 | (s/validate Message message) 195 | (let [stream (java.io.ByteArrayOutputStream.) 196 | envelope (string->bytes (cheshire/generate-string (message->envelope message))) 197 | chunks (into [] 198 | (remove nil? [{:descriptor {:type 1} 199 | :data envelope} 200 | (get-in message [:_chunks :data]) 201 | (get-in message [:_chunks :debug])]))] 202 | (b/encode message-codec stream {:chunks chunks}) 203 | (.toByteArray stream))) 204 | 205 | (s/defn decode :- Message 206 | "Returns a message object from a network format message" 207 | [bytes :- ByteArray] 208 | (let [stream (java.io.ByteArrayInputStream. bytes) 209 | decoded (try+ 210 | (binding [*message-data-length* (alength bytes)] 211 | (b/decode message-codec stream)) 212 | (catch Throwable _ 213 | (throw+ {:type ::message-malformed 214 | :message (:message &throw-context)})))] 215 | (if (not (= 1 (get-in (first (:chunks decoded)) [:descriptor :type]))) 216 | (throw+ {:type ::message-invalid 217 | :message (i18n/trs "first chunk should be type 1")})) 218 | (let [envelope-json (bytes->string (:data (first (:chunks decoded)))) 219 | envelope (try+ 220 | (cheshire/decode envelope-json true) 221 | (catch Exception _ 222 | (throw+ {:type ::envelope-malformed 223 | :message (:message &throw-context)}))) 224 | data-chunk (second (:chunks decoded)) 225 | data-frame (or (:data data-chunk) empty-byte-array) 226 | data-flags (or (get-in data-chunk [:descriptor :flags]) #{})] 227 | (try+ (s/validate v1-Envelope envelope) 228 | (catch Object _ 229 | (throw+ {:type ::envelope-invalid 230 | :message (:message &throw-context)}))) 231 | (let [message (set-data (merge (make-message) envelope) data-frame data-flags)] 232 | (if-let [debug-chunk (get (:chunks decoded) 2)] 233 | (let [debug-frame (or (:data debug-chunk) empty-byte-array) 234 | debug-flags (or (get-in debug-chunk [:descriptor :flags]) #{})] 235 | (set-debug message debug-frame debug-flags)) 236 | message))))) 237 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 2015 Puppet Labs 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. 202 | 203 | --------------------------------------------------------------------------------