UNPKG

11.9 kBMarkdownView Raw
1---
2permalink: /docs/patterns/
3---
4
5# Patterns
6
7Shared patterns for dealing with common Hubot scenarios.
8
9## Renaming the Hubot instance
10
11When you rename Hubot, he will no longer respond to his former name. In order to train your users on the new name, you may choose to add a deprecation notice when they try to say the old name. The pattern logic is:
12
13* listen to all messages that start with the old name
14* reply to the user letting them know about the new name
15
16Setting this up is very easy:
17
181. Create a [bundled script](scripting.md) in the `scripts/` directory of your Hubot instance called `rename-hubot.coffee`
192. Add the following code, modified for your needs:
20
21```coffeescript
22# Description:
23# Tell people hubot's new name if they use the old one
24#
25# Commands:
26# None
27#
28module.exports = (robot) ->
29 robot.hear /^hubot:? (.+)/i, (res) ->
30 response = "Sorry, I'm a diva and only respond to #{robot.name}"
31 response += " or #{robot.alias}" if robot.alias
32 res.reply response
33 return
34
35```
36
37In the above pattern, modify both the hubot listener and the response message to suit your needs.
38
39Also, it's important to note that the listener should be based on what hubot actually hears, instead of what is typed into the chat program before the Hubot Adapter has processed it. For example, the [HipChat Adapter](https://github.com/hipchat/hubot-hipchat) converts `@hubot` into `hubot:` before passing it to Hubot.
40
41## Deprecating or Renaming Listeners
42
43If you remove a script or change the commands for a script, it can be useful to let your users know about the change. One way is to just tell them in chat or let them discover the change by attempting to use a command that no longer exists. Another way is to have Hubot let people know when they've used a command that no longer works.
44
45This pattern is similar to the Renaming the Hubot Instance pattern above:
46
47* listen to all messages that match the old command
48* reply to the user letting them know that it's been deprecated
49
50Here is the setup:
51
521. Create a [bundled script](scripting.md) in the `scripts/` directory of your Hubot instance called `deprecations.coffee`
532. Copy any old command listeners and add them to that file. For example, if you were to rename the help command for some silly reason:
54
55```coffeescript
56# Description:
57# Tell users when they have used commands that are deprecated or renamed
58#
59# Commands:
60# None
61#
62module.exports = (robot) ->
63 robot.respond /help\s*(.*)?$/i, (res) ->
64 res.reply "That means nothing to me anymore. Perhaps you meant `docs` instead?"
65 return
66
67```
68
69## Preventing Hubot from Running Scripts Concurrently
70
71Sometimes you have scripts that take several minutes to execute. If these scripts are doing something that could be interfered
72with by running subsequent commands, you may wish to code your scripts to prevent concurrent access.
73
74To do this, you can set up a lock in the Hubot [brain](scripting.md#persistence) object. The lock is set up here so that different scripts
75can share the same lock if necessary.
76
77Setting up the lock looks something like this:
78
79```coffeescript
80module.exports = (robot) ->
81 robot.brain.on 'loaded', ->
82 # Clear the lock on startup in case Hubot has restarted and Hubot's brain has persistence (e.g. redis).
83 # We don't want any orphaned locks preventing us from running commands.
84 robot.brain.remove('yourLockName')
85
86 robot.respond /longrunningthing/i, (msg) ->
87 lock = robot.brain.get('yourLockName')
88
89 if lock?
90 msg.send "I'm sorry, #{msg.message.user.name}, I'm afraid I can't do that. I'm busy doing something for #{lock.user.name}."
91 return
92
93 robot.brain.set('yourLockName', msg.message) # includes user, room, etc about who locked
94
95 yourLongClobberingAsyncThing (err, response) ->
96 # Clear the lock
97 robot.brain.remove('yourLockName')
98 msg.reply "Finally Done"
99```
100
101## Forwarding all HTTP requests through a proxy
102
103In many corporate environments, a web proxy is required to access the Internet and/or protected resources. For one-off control, use can specify an [Agent](https://nodejs.org/api/http.html) to use with `robot.http`. However, this would require modifying every script your robot uses to point at the proxy. Instead, you can specify the agent at the global level and have all HTTP requests use the agent by default.
104
105Due to the way node.js handles HTTP and HTTPS requests, you need to specify a different Agent for each protocol. ScopedHTTPClient will then automatically choose the right ProxyAgent for each request.
106
1071. Install ProxyAgent. `npm install proxy-agent`
1082. Create a [bundled script](scripting.md) in the `scripts/` directory of your Hubot instance called `proxy.coffee`
1093. Add the following code, modified for your needs:
110
111```coffeescript
112proxy = require 'proxy-agent'
113module.exports = (robot) ->
114 robot.globalHttpOptions.httpAgent = proxy('http://my-proxy-server.internal', false)
115 robot.globalHttpOptions.httpsAgent = proxy('http://my-proxy-server.internal', true)
116```
117
118## Dynamic matching of messages
119
120In some situations, you want to dynamically match different messages (e.g. factoids, JIRA projects). Rather than defining an overly broad regular expression that always matches, you can tell Hubot to only match when certain conditions are met.
121
122In a simple robot, this isn't much different from just putting the conditions in the Listener callback, but it makes a big difference when you are dealing with middleware: with the basic model, middleware will be executed for every match of the generic regex. With the dynamic matching model, middleware will only be executed when the dynamic conditions are matched.
123
124For example, the [factoid lookup command](https://github.com/github/hubot-scripts/blob/bd810f99f9394818a9dcc2ea3729427e4101b96d/src/scripts/factoid.coffee#L95-L99) could be reimplemented as:
125
126```coffeescript
127module.exports = (robot) ->
128 # Dynamically populated list of factoids
129 facts =
130 fact1: 'stuff'
131 fact2: 'other stuff'
132
133 robot.listen(
134 # Matcher
135 (message) ->
136 match = message.match(/^~(.*)$/)
137 # Only match if there is a matching factoid
138 if match and match[1] in facts
139 match[1]
140 else
141 false
142 # Callback
143 (response) ->
144 fact = response.match
145 res.reply "#{fact} is #{facts[fact]}"
146 )
147```
148
149## Restricting access to commands
150
151One of the awesome features of Hubot is its ability to make changes to a production environment with a single chat message. However, not everyone with access to your chat service should be able to trigger production changes.
152
153There are a variety of different patterns for restricting access that you can follow depending on your specific needs:
154
155* Two buckets of access: full and restricted with whitelist/blacklist
156* Specific access rules for every command (Role-based Access Control)
157* Blacklisting/whitelisting commands in specific rooms
158
159### Simple per-listener access
160
161In some organizations, almost all employees are given the same level of access and only a select few need to be restricted (e.g. new hires, contractors, etc.). In this model, you partition the set of all listeners to separate the "power commands" from the "normal commands".
162
163Once you have segregated the listeners, you need to make some tradeoff decisions around whitelisting/blacklisting users and listeners.
164
165The key deciding factors for whitelisting vs blacklisting of users are the number of users in each category, the frequency of change in either category, and the level of security risk your organization is willing to accept.
166* Whitelisting users (users X, Y, Z have access to power commands; all other users only get access to normal commands) is a more secure method of access (new users have no default access to power commands), but has higher maintenance overhead (you need to add each new user to the "approved" list).
167* Blacklisting users (all users get access to power commands, except for users X, Y, Z, who only get access to normal commands) is a less secure method (new users have default access to power commands until they are added to the blacklist), but has a much lower maintenance overhead if the blacklist is small/rarely updated.
168
169The key deciding factors for selectively allowing vs restricting listeners are the number of listeners in each category, the ratio of internal to external scripts, and the level of security risk your organization is willing to accept.
170* Selectively allowing listeners (all listeners are power commands, except for listeners A, B, C, which are considered normal commands) is a more secure method (new listeners are restricted by default), but has a much higher maintenance overhead (every silly/fun listener needs to be explicity downgraded to "normal" status).
171* Selectively restricting listeners (listeners A, B, C are power commands, everything else is a normal command) is a less secure method (new listeners are put into the normal category by default, which could give unexpected access; external scripts are particularly scary here), but has a lower maintenance overhead (no need to modify/enumerate all the fun/culture scripts in your access policy).
172
173As an additional consideration, most scripts do not currently have listener IDs, so you will likely need to open PRs (or fork) any external scripts you use to add listener IDs. The actual modification is easy, but coordinating with lots of maintainers can be time consuming.
174
175Once you have decided which of the four possible models to follow, you need to build the appropriate lists of users and listeners to plug into your authorization middleware.
176
177Example: whitelist of users given access to selectively restricted power commands
178```coffeescript
179POWER_COMMANDS = [
180 'deploy.web' # String that matches the listener ID
181]
182
183POWER_USERS = [
184 'jdoe' # String that matches the user ID set by the adapter
185]
186
187module.exports = (robot) ->
188 robot.listenerMiddleware (context, next, done) ->
189 if context.listener.options.id in POWER_COMMANDS
190 if context.response.message.user.id in POWER_USERS
191 # User is allowed access to this command
192 next()
193 else
194 # Restricted command, but user isn't in whitelist
195 context.response.reply "I'm sorry, @#{context.response.message.user.name}, but you don't have access to do that."
196 done()
197 else
198 # This is not a restricted command; allow everyone
199 next()
200```
201
202Remember that middleware executes for ALL listeners that match a given message (including `robot.hear /.+/`), so make sure you include them when categorizing your listeners.
203
204### Specific access rules per listener
205
206For larger organizations, a binary categorization of access is usually insufficient and more complex access rules are required.
207
208Example access policy:
209* Each development team has access to cut releases and deploy their service
210* The Operations group has access to deploy all services (but not cut releases)
211* The front desk cannot cut releases nor deploy services
212
213Complex policies like this are currently best implemented in code directly, though there is [ongoing work](https://github.com/michaelansel/hubot-rbac) to build a generalized framework for access management.
214
215### Specific access rules per room
216
217Organizations that have a number of chat rooms that serve different purposes often want to be able to use the same instance of hubot but have a different set of commands allowed in each room.
218
219Work on generalized blacklist solution is [ongoing](https://github.com/kristenmills/hubot-command-blacklist). A whitelist soultion could take a similar approach.
220
221## Use scoped npm packages as adapter
222
223It is possible to [install](https://docs.npmjs.com/cli/v7/commands/npm-install) package under a custom alias:
224
225```bash
226npm install <alias>@npm:<name>
227```
228
229So for example to use `@foo/hubot-adapter` package as the adapter, you can:
230```bash
231npm install hubot-foo@npm:@foo/hubot-adapter
232
233bin/hubot --adapter foo
234```